Delving into the wonderful world of .NET databinding. I have a textbox whose text property I want to bind to a specific element of a string array in another object. (The form contains a combobox that selects the index of the element).
In other words, I'd like to do something like this:
textBoxFictionShort.DataBindings.Add(
new Binding("Text", m_Scenario, "Fiction[int32.Parse(comboBoxSelector.Text)]"));
where m_Scenario contains the
public string[] Fiction { get; set; }
property that I source from. Obviously the Binding above won't retrieve my item. AFAIK I can't create properties that accept parameters. What's the elegant/correct solution for this when using databinding? I can think of several ugly-seeming workarounds (i.e. a string property in m_Scenario that references the array string I'm binding to, and a public function that updates the string property on the combobox SelectedIndexChanged event).
This is an excellent place to have a View Model. Here's another ViewModel link
What I would do is have the following in the ViewModel (that gets bound to by components on the view)
an IObservable property bound to the items source of the combo box, that you add/remove to depending on the size of the array
a int property for the selected index bound to the SelectedElement of the combo box. You would have to do the conversion from string to int when this property is being set.
a string property that is bound to the textbox.text (you could likely use a label here, by the by) that is updated each time the aforementioned int property for the selected index is changed.
If this at all confusing I can build up some pseudo code, but those three properties should work and get you what you want.
Edit - To add some code:
public class YourViewModel : DependencyObject {
public string[] FictionArray {get; private set;}
public IObservable<string> AvailableIndices;
public static readonly DependencyProperty SelectedIndexProperty=
DependencyProperty.Register("SelectedIndex", typeof(string), typeof(YourViewModel), new PropertyMetadata((s,e) => {
var viewModel = (YourViewModel) s;
var index = Convert.ToInt32(e.NewValue);
if (index >= 0 && index < viewModel.FictionArray.Length)
viewModel.TextBoxText=FictionArray[index];
}));
public bool SelectedIndex {
get { return (bool)GetValue(SelectedIndexProperty); }
set { SetValue(SelectedIndexProperty, value); }
}
public static readonly DependencyProperty TextBoxTextProperty=
DependencyProperty.Register("TextBoxText", typeof(string), typeof(YourViewModel));
public bool TextBoxText {
get { return (bool)GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
public YourViewModel(string[] fictionArray) {
FictionArray = fictionArray;
for (int i = 0; i < FictionArray.Length; i++){
AvailableIndices.Add(i.ToString()));
}
}
}
This isn't perfect, but it should give you some idea how you could create a viewmodel with properties that you could bind to. So in your xaml you'd have something like:
<ComboBox ItemSource="{Binding AvailableIndices}" SelectedItem="{Binding SelectedIndex}"/>
<TextBox Text="{Binding TextBoxText}"/>
I think you are in WinForms (not WPF), in this case you could just bind directly to the ComboBox's SelectedValue property...
comboBox1.DataSource = m_Scenario.Fiction;
textBoxFictionShort.DataBindings.Add(new Binding("Text", comboBox1, "SelectedValue"));
Add BindingSource
...
bindingSource1.DataSource = m_Scenario.Fiction
.Select((x, i) => new {Key = i + 1, Value = x})
.ToDictionary(x => x.Key, x => x.Value);
comboBox1.DisplayMember = "Key";
comboBox1.DataSource = bindingSource1;
textBox1.DataBindings.Add("Text", bindingSource1, "Value");
}
}
Related
I have a combobox that's set to DropDownStyle=DropDownList (meaning users can't type anything, just select from dropdown). The combo contains a list of states.
I am trying to bind the selected text value to _model.StateBar, but my code doesn't seem to update the property of the object.
I've tried both of the following:
cboStates.DataBindings.Add("Text", _model, "StateBar")
cboStates.DataBindings.Add("SelectedItem", _model, "StateBar")
cboStates.DataBindings.Add("SelectedValue", _model, "StateBar")
I just need to bind it one way: updates from the control need to end up on the object.
Binding to ComboBox.SelectedValue should work, but only in case when you add items through ComboBox.DataSource.
public class Model
{
public string StateBar { get; set; }
}
// In the form
var states = new List<string> { "Alabama", "California" };
combobox.DataSource = states;
combobox.DataBindings.Add("SelectedValue", _model, "StateBar", true, DataSourceUpdateMode.OnPropertyChanged);
Binding to SelectedItem should work in all cases.
I am trying to populate my combobox from a service response. The service returns an array of object like following
MyService.FirmSocial[] firmSocialList = client.GetActiveSocialMediaTypes();
I have checked, the firmSocialList populates properly. I need to populate my combobox with these values.
I have tried this in my code behind
cbSocialMediaTypes.ItemsSource = firmSocialList;
cbSocialMediaTypes.DisplayMemberPath = "socialMediaValue";
cbSocialMediaTypes.SelectedValuePath = "socialMediaType";
I also tried the same thing on the XAML side, but all I am getting is bunch of empty strings in my combobox. The thing is though, the number of elements matches with the item count of the combobox (of empty strings).
And yes, the property names of the FirmSocial object is correct.
The FirmSocial class
public class FirmSocial
{
private int socialMediaType;
private string socialMediaValue;
public int SocialMediaType
{
get
{
return socialMediaType;
}
set
{
socialMediaType = value;
}
}
public string SocialMediaValue
{
get
{
return socialMediaValue;
}
set
{
socialMediaValue = value;
}
}
}
And I have also tried this in my XAML section;
<ComboBox x:Name="cbSocialMediaTypes" HorizontalAlignment="Left" Margin="56,8,0,0" VerticalAlignment="Top" Width="211"
ItemsSource="{Binding firmSocialList}"
DisplayMemberPath="socialMediaType"
SelectedValuePath="socialMediaType" />
Thanks.
DisplayMemberPath is case sensitive.
DisplayMemberPath="socialMediaType"
is saying trying to bind to your private field, not your public property. Try:
DisplayMemberPath="SocialMediaType"
The problem is that you set the DisplayMemberPath and the SelectedValuePath to a private fields instead of a public properties.
cbSocialMediaTypes.DisplayMemberPath = "socialMediaValue";
cbSocialMediaTypes.SelectedValuePath = "socialMediaType";
Change it to
cbSocialMediaTypes.DisplayMemberPath = "SocialMediaValue";
cbSocialMediaTypes.SelectedValuePath = "SocialMediaType";
I have a class containing details of my customer.
class CustomerData : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get
{ return _Name }
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
// Lots of other properties configured.
}
I also have a list of CustomerData values List<CustomerData> MyData;
I currently databinding an individual CustomerData object to textboxes in the below way which works fine.
this.NameTxtBox.DataBindings.Add("Text", MyCustomer, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
I'm struggling to find a way to bind each object in the list MyData to a ListBox.
I want to have each object in the MyData list in displayed in the ListBox showing the name.
I have tried setting the DataSource equal to the MyData list and setting the DisplayMember to "Name" however when i add items to the MyData list the listbox does not update.
Any ideas on how this is done?
I found that List<T> will not allow updating of a ListBox when the bound list is modified.
In order to get this to work you need to use BindingList<T>
BindingList<CustomerData> MyData = new BindingList<CustomerData>();
MyListBox.DataSource = MyData;
MyListBox.DisplayMember = "Name";
MyData.Add(new CustomerData(){ Name = "Jimmy" } ); //<-- This causes the ListBox to update with the new entry Jimmy.
I still see my self as a beginner developer when it comes to wpf. I would like to know 2 things
where I went wrong or
how can I troubleshoot to find the solution.
Situation: [DATA part] I Have:
DataModel object. DataFilter object which is basically collection of DataModels + added functions. and DataFiltersGroup, which is used in DataViewModel and has collection of DataFilters I have a DataViewModel object which is basically an observable collection of items. I want to display each DataFilter in an Itemscontrol.
[Current solution] I have build a specialcombo control which derives from combobox [basically a button +combobox]. The specialcombo works fine when deliberately bound. So I am fairly confident the problem is not with special combo. When I set ItemsControl.ItemsSource property to the collection of DataFilters and make a DataTemplate of SpecialCombo, the combobox does not show any result (Special combo will not show toggle button if there are no Items - only button will show). An alternative - approach (2) to binding below let me see the dropdown togglebutton, but dropdown is empty however I know it shouldn't be.
here is sumarized extracts of code
public class DataModel :INotifyPropertyChanged
{
//The Item!!
public int Index {//Normal get set property}
public string Name {//Normal get set property}
public int Parent {//Normal get set property}
public string FullName {//Normal get set property}
public string DisplayName {//Normal get set property}
public bool Static {//Normal get set property}
}
public class DataFilters : DataCollection
{
public ObservableCollection<DataModel> CombinedData;
public int FilterIndex{//Property... The index of the current item like Index for DataModel.}
public string ParentName {//property ButtonContent item}
public int SelectedItem {//Property}
}
//Used as part of DataVieModel. Also responsible of building each DataFilters item and some other functions
public class DataFilterGroup : INotifyPropertyChanged
{
public ObservableCollection<DataFilters> FullCollection;
}
The WPF object
<ItemsControl x:Name="PART_ListBox" HorizontalAlignment="Left" VerticalContentAlignment="Stretch" Margin="0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Code behind for WPF on load
//DVM = DataVieModel with some other objects. Filters = DataFilterGroup
PART_ListBox.ItemsSource = DVM.Filters.FullCollection;
PART_ListBox.ItemTemplate = DataFilterTemplate;
//And DataTemplate (1) - shows no combobox
private static DataTemplate DataFilterTemplate
{
get
{
DataTemplate DFT = new DataTemplate();
DFT.DataType = typeof(DataFilters);
FrameworkElementFactory Stack = new FrameworkElementFactory(typeof(VirtualizingStackPanel));
Stack.SetValue(VirtualizingStackPanel.OrientationProperty, Orientation.Horizontal);
FrameworkElementFactory Item = new FrameworkElementFactory(typeof(SpecialCombo));
Item.SetValue(SpecialCombo.ButtonContentProperty, new Binding("ParentName"));
Item.SetValue(SpecialCombo.ItemsSourceProperty, "CombinedData");
Item.SetValue(SpecialCombo.DisplayMemberPathProperty, "DisplayName");
Item.SetValue(SpecialCombo.SelectedValuePathProperty, "Index");
Item.SetValue(SpecialCombo.SelectedValueProperty, "SelectedItem");
//Item.SetValue(SpecialCombo.ToggleVisibleProperty, new Binding("ComboVisibility"));
//Item.SetValue(SpecialCombo.SelectedValueProperty, new Binding("SelectedItem"));
Stack.AppendChild(Item);
DFT.VisualTree = Stack;
return DFT;
}
}
//And DataTemplate (2) - shows combobox with no items in dropdown
private static DataTemplate DataFilterTemplate
{
get
{
DataTemplate DFT = new DataTemplate();
DFT.DataType = typeof(DataFilters);
FrameworkElementFactory Stack = new FrameworkElementFactory(typeof(VirtualizingStackPanel));
Stack.SetValue(VirtualizingStackPanel.OrientationProperty, Orientation.Horizontal);
FrameworkElementFactory Item = new FrameworkElementFactory(typeof(SpecialCombo));
Item.SetValue(SpecialCombo.ButtonContentProperty, new Binding("ParentName"));
Item.SetValue(SpecialCombo.ItemsSourceProperty, new Binding("CombinedData"));
Item.SetValue(SpecialCombo.DisplayMemberPathProperty, "DisplayName");
Item.SetValue(SpecialCombo.SelectedValuePathProperty, "Index");
Item.SetValue(SpecialCombo.SelectedValueProperty, "SelectedItem");
//Item.SetValue(SpecialCombo.ToggleVisibleProperty, new Binding("ComboVisibility"));
//Item.SetValue(SpecialCombo.SelectedValueProperty, new Binding("SelectedItem"));
Stack.AppendChild(Item);
DFT.VisualTree = Stack;
return DFT;
}
}
Thanks to punker 76 in another post where I restructured the question (here -> Can one bind a combobox Itemssource from a datatemplate of a ItemsControl) slightly the following had to be done.
DataFilters should become a dependencyobject therefore
public class DataFilters : DataCollection
// should become
public class DataFilters : DependencyObject
Observalbe collection should also change. so
public ObservableCollection<DataModel> CombinedData;
// should become
public static readonly DependencyProperty CombinedData= DependencyProperty.Register("CombinedData", typeof(ObservableCollection<DataModel>), typeof(DataFilters), new FrameworkPropertyMetadata());
//and should become a property
public ObservableCollection<DataModel> CombinedData
{
get { return (ObservableCollection<DataModel>)GetValue(CombinedDataProperty); }
set { SetValue(CombinedDataProperty, value); }
}
Then in the DataTemplate file the following should change
Item.SetValue(SpecialCombo.ItemsSourceProperty, "CombinedData");
//Should change to
Item.SetBinding(SpecialCombo.ItemsSourceProperty, new Binding("CombinedData") );
I haven't gone through the entire code above, but I think all the above changes should all be needed in order to bind a combobox type item in a DataTemplate.
I have a ComboBox with few static values.
<ComboBox Name="cmbBoxField" Grid.Column="4" Grid.Row="2" Style="{StaticResource comboBoxStyleFixedWidth}" ItemsSource="{Binding}" ></ComboBox>
MVVMModle1.cmbBoxField.Items.Add(new CustomComboBoxItem("Text Box", "0"));
MVVMModle1.cmbBoxFieldType.Items.Add(new CustomComboBoxItem("Pick List", "1"));
MVVMModle1.cmbBoxFieldType.Items.Add(new CustomComboBoxItem("Check Box", "2"));
MVVMModle1.cmbBoxFieldType.Items.Add(new CustomComboBoxItem("Radio Button", "3"));
When I am saving the data in Database table it is getting saved.
((CustomComboBoxItem)(MVVMModle1.cmbBoxField.SelectedValue)).Value.ToString();
Now when I am trying to Edit my form and binding the value again to combobox it is not showing the value.
MVVMModle1.cmbBoxField.SelectedValue = dtDataList.Rows[0]["ControlList"].ToString().Trim();
Someone please help me in this. How to bind selected value to the combobox?
There are quite a few problems with your code here:
You are setting the ItemsControl.ItemsSource property to the default binding (bind to the current data context), which is incorrect unless the DataContext is any type that implements IEnumerable, which it probably isn't.
If this is correct because the DataContext is, for example, an ObservableCollection<T>, then you still have an issue because you are adding items statically to the ComboBox instead of whatever the ItemsSource is.
Also, the type of items you are adding are CustomComboBoxItem, which I'm going to assume inherits from ComboBoxItem. Either way, you can't say the SelectedValue is some string since the values in the ComboBox are not strings.
You should really not have a collection of CustomComboBoxItem's, but instead a custom class that is in itself it's own ViewModel.
Now that that's been said, here is a suggested solution to your problem:
<ComboBox ItemsSource="{Binding Path=MyCollection}"
SelectedValue="{Binding Path=MySelectedString}"
SelectedValuePath="StringProp" />
public class CustomComboBoxItem : ComboBoxItem
{
// Not sure what the property name is...
public string StringProp { get; set; }
...
}
// I'm assuming you don't have a separate ViewModel class and you're using
// the actual window/page as your ViewModel (which you shouldn't do...)
public class MyWPFWindow : Window, INotifyPropertyChanged
{
public MyWPFWindow()
{
MyCollection = new ObservableCollection<CustomComboBoxItem>();
// Add values somewhere in code, doesn't have to be here...
MyCollection.Add(new CustomComboBoxItem("Text Box", "0"));
etc ...
InitializeComponent();
}
public ObservableCollection<CustomComboBoxItem> MyCollection
{
get;
private set;
}
private string _mySelectedString;
public string MySelectedString
{
get { return _mySelectedString; }
set
{
if (String.Equals(value, _mySelectedString)) return;
_mySelectedString = value;
RaisePropertyChanged("MySelectedString");
}
}
public void GetStringFromDb()
{
// ...
MySelectedString = dtDataList.Rows[0]["ControlList"].ToString().Trim();
}
}
You could alternatively not implement INotifyPropertyChanged and use a DependencyProperty for your MySelectedString property, but using INPC is the preferred way. Anyways, that should give you enough information to know which direction to head in...
TL;DR;
Take advantage of binding to an ObservableCollection<T> (create a property for this).
Add your items (CustomComboBoxItems) to the ObservableCollection<T>.
Bind the ItemsSource to the new collection property you created.
Bind the SelectedValue to some string property you create (take advantage of INPC).
Set the SelectedValuePath to the path of the string property name of your CustomComboBoxItem.
Can you use cmbBoxField.DataBoundItem()? If not target the source from the selected value, i.e. Get the ID then query the source again to get the data.
(CustomComboBoxItem)MVVMModle1.cmbBoxField.DataBoundItem();
When you bind a datasource it is simpler to do it like this:
private List GetItems(){
List<CustomComboBoxItem> items = new List<CustomComboBoxItem>();
items.Add(new CustomComboBoxItem() {Prop1 = "Text Box", Prop2 = "0"});
//...and so on
return items;
}
Then in your main code:
List<CustomComboBoxItem> items = this.GetItems();
MVVMModle1.cmbBoxField.DisplayMember = Prop1;
MVVMModle1.cmbBoxField.ValueMember = Prop2;
MVVMModle1.cmbBoxField.DataSource = items;
This will then allow your selected value to work, either select by index, value or text
var selected = dtDataList.Rows[0]["ControlList"].ToString().Trim();
MVVMModle1.cmbBoxField.SelectedValue = selected;