I am working on a textbox and combobox in my wpf app. I am sorry for weird title. Well here is the scenario:
Xaml:
<ComboBox ItemsSource="{Binding PortModeList}" SelectedItem="{Binding SelectedPortModeList, Mode=OneWayToSource}" SelectedIndex="0" Name="PortModeCombo" />
<TextBox Grid.Column="1" Text="{Binding OversampleRateBox}" Name="HBFilterOversampleBox" />
ViewModel Class:
public ObservableCollection<string> PortModeList
{
get { return _PortModeList; }
set
{
_PortModeList = value;
OnPropertyChanged("PortModeList");
}
}
private string _selectedPortModeList;
public string SelectedPortModeList
{
get { return _selectedPortModeList; }
set
{
_selectedPortModeList = value;
OnPropertyChanged("SelectedPortModeList");
}
}
private string _OversampleRateBox;
public string OversampleRateBox
{
get
{
return _OversampleRateBox;
}
set
{
_OversampleRateBox = value;
OnPropertyChanged("OversampleRateBox");
}
}
Here I have three requirements:
-
By using
SelectedIdin xaml I am able to select the id but I want to set the selectedid of my combobox from viewmodel class. I.e.
int portorder = 2. How can I do something like this? or is their any other approach?
PortModeList->SetSelectedId(portOrder) -
I need to restrict number of entries inside a textbox to 4. I.e. 1234 is entered in textbox, it should not let user exceed 4 digits.
-
I want to set the format of text in
OversampleRateBoxas: 0x__. I.e. if user wants to enter 23 present in a variable, then I shud set text as 0x23. Basically 0x should be present at the beginning.
Please help 🙂
I would use the
SelectedItemproperty of theComboBox(as you are doing), but make the binding two-way. Then, you can set yourSelectedPortModeList(which should be calledSelectedPortMode) in your view model.In the view model:
If you want to limit the number of characters in a
TextBox, then use theMaxLengthproperty:If you wish to add a prefix to the
OversampleRateBox, one option would be to test for the presence of this in the setter forOversampleRateBox, and if it’s not there, then add it before assigning to your private field.Update
Bind your
TextBoxto a string property:In the setter for your property, check that the input is valid before setting your private field:
Because the binding is two-way, you can also set the value from your view model code (for example in the view model constructor):