ComboBox SelectedItem Binding - c#

I have a ComboBox in my View:
<ComboBox Name="comboBox1" ItemsSource="{Binding MandantList}" SelectedItem="{Binding CurrentMandant, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Firma}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Here is my Model:
public class MandantListItem : INotifyPropertyChanged
{
public MandantListItem() { }
string _Firma;
bool _IsChecked;
public string Firma
{
get { return _Firma; }
set { _Firma = value; }
}
public bool IsChecked
{
get
{
return _IsChecked;
}
set
{
_IsChecked = value;
OnPropertyChanged(nameof(IsChecked));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And here is my ViewModel:
public class MaViewModel : INotifyPropertyChanged
{
public ObservableCollection<MandantListItem> MandantList { get { return _MandantList; } }
public ObservableCollection<MandantListItem> _MandantList = new ObservableCollection<MandantListItem>();
private MandantListItem _CurrentMandant;
public MandantListItem CurrentMandant
{
get { return _CurrentMandant; }
set
{
if (value != _CurrentMandant)
{
_CurrentMandant = value;
OnPropertyChanged("CurrentMandant");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
How to fill the ComboBox:
public zTiredV2.ViewModel.MaViewModel MAList = new zTiredV2.ViewModel.MaViewModel();
this.comboBox1.ItemsSource = MAList.MandantList;
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "A", Homepage = "a.com", IsChecked = false });
MAList.MandantList.Add(new zTiredV2.Model.MandantListItem { Firma = "B", Homepage = "b.com", IsChecked = false });
But my item doesnt update ... tried also via IsChecked, but no success either ... when i iterate through MAList, IsChecked is always false. And how can i bind a TextBlock to the selected Firma?
Have a hard time with MVVM, but i like it.

You should set the DataContext of the ComboBox to an instance of your view model. Otherwise the bindings won't work:
this.comboBox1.DataContext = MAList;
Also note that the _MandantList backing field for your property shouldn't be public. In fact, you don't need it at all:
public ObservableCollection<MandantListItem> MandantList { get; } = new ObservableCollection<MandantListItem>();
Setting the DataContext should cause the CurrentMandant property to get set when you select an item in the ComboBox. It won't set the IsChecked property though.

Related

Binding in ListBox of checkboxes where ItemSource is collection

I've got ComboBox and ListBox of CheckBoxes. Depending on SelectedItem of ComboBox ItemSource of ListBox must change. I made a sample to make thing easier. Here is the code:
ViewModel
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Test
{
class Data
{
public long Id;
public object Value;
public override string ToString()
{
return Value.ToString();
}
}
class CheckedData: INotifyPropertyChanged
{
private Data myData;
public Data MyData
{
get { return myData; }
set
{
if (myData == value)
return;
myData = value;
RaisePropertyChanged(nameof(MyData));
}
}
private bool isChecked;
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
RaisePropertyChanged(nameof(IsChecked));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class BindingObject: INotifyPropertyChanged
{
private ObservableCollection<Data> dataList = new ObservableCollection<Data>();
public ObservableCollection<Data> DataList
{
get { return dataList; }
set
{
dataList = value;
RaisePropertyChanged(nameof(DataList));
}
}
private Data selectedItem;
public Data SelectedItem
{
get { return selectedItem; }
set
{
if (value == selectedItem)
return;
selectedItem = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class ViewModel: INotifyPropertyChanged
{
public ViewModel()
{
var tmp = new Data() {Id = 1, Value = "Cat"};
Obj.DataList.Add(tmp);
Obj.SelectedItem = tmp;
Obj.DataList.Add(new Data() {Id = 2, Value = "Dog"});
Mapping[1] = new ObservableCollection<CheckedData>()
{
new CheckedData() {IsChecked = true, MyData = new Data() {Id = 1, Value = "Maine coon"}},
new CheckedData() {IsChecked = true, MyData = new Data() {Id = 2, Value = "Siberian"}}
};
}
private BindingObject obj = new BindingObject();
public BindingObject Obj
{
get { return obj; }
set
{
if (obj == value)
return;
obj = value;
RaisePropertyChanged(nameof(Obj));
}
}
private Dictionary<long, ObservableCollection<CheckedData>> mapping = new Dictionary<long, ObservableCollection<CheckedData>>();
public Dictionary<long, ObservableCollection<CheckedData>> Mapping
{
get { return mapping; }
set
{
if (mapping == value)
return;
mapping = value;
RaisePropertyChanged(nameof(Mapping));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
View
<ComboBox x:Name="comboBox" ItemsSource="{Binding Path=Obj.DataList}" SelectedItem="{Binding Path=Obj.SelectedItem, Mode=TwoWay}"/>
<ListBox x:Name="listBox" Height="100" ItemsSource="{Binding Path=Mapping[Obj.SelectedItem.Id]}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Path=MyData.Value}" Margin="0,5,5,0"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
That is what I thought should work. ComboBox is okay, but ListBox ItemSource binding doesn't work. Only if I bind directly to list like this:
ViewModel
private ObservableCollection<CheckedData> test = new ObservableCollection<CheckedData>()
{
new CheckedData() {IsChecked = true, MyData = new Data() {Id = 1, Value = "Maine coon"}},
new CheckedData() {IsChecked = false, MyData = new Data() {Id = 2, Value = "Siberian"}}
};
public ObservableCollection<CheckedData> Test
{
get { return test; }
set
{
test = value;
RaisePropertyChanged(nameof(Test));
}
}
View
<ListBox x:Name="listBox" Height="100" ItemsSource="{Binding Path=Test}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Path=MyData.Value}" Margin="0,5,5,0"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Everything starts working.. Except Content binding, because I can't go deeper than 1 level of property path. So I have to override ToString() method in Data.
What should I fix to make everything work? Am I able to bind ItemSource like this? Why can't I go deeper than 1 lvl property binding in CheckBox?
Am I able to bind ItemSource like this?
No, this kind of bindings are not supported in XAML:
Binding Path=Mapping[Obj.SelectedItem.Id].
You must replace Obj.SelectedItem.Id with a constant key value like 1 or bind to some other property that returns the collection of items.
Everything starts working.. Except Content binding
You can only bind to public properties so Value must be a property and not a field:
class Data
{
public long Id { get; set; }
public object Value { get; set; }
}
You can achive this easy with:
public ObservableCollection<CheckedData> SelectedData
{
get
{
return Mapping[Obj.SelectedItem.Id];
}
}
And into
public Data SelectedItem
{
get { return selectedItem; }
set
{
if (value == selectedItem)
return;
selectedItem = value;
RaisePropertyChanged(nameof(SelectedData)); // add this.
}
}
Now, in XAML, you can easy:
<ListBox x:Name="listBox" Height="100" ItemsSource="{Binding Path=Obj.SelectedData}">

Check Box binding WPF

I have 3 checkboxes. Lets call them cb1,cb2 and cb3. The cb3 should be checkëd when cb1 and cb2 are checked. How do I Implement this in WPF.? I am new to WPF.
Thanks in advance.
If you are using a ViewModel, just add a new computed property to that.
A simple view model would look like:
public class MyVieWModel : INotifyPropertyChanged
{
private bool _cb1Checked;
private bool _cb2Checked;
public bool CB1Checked
{
get { return _cb1Checked; }
set
{
_cb1Checked = value;
PropertyChanged(this, new PropertyChangedEventArgs("CB1Checked"));
PropertyChanged(this, new PropertyChangedEventArgs("CB3Checked"));
}
}
public bool CB2Checked
{
get { return _cb2Checked; }
set
{
_cb2Checked = value;
PropertyChanged(this, new PropertyChangedEventArgs("CB2Checked"));
PropertyChanged(this, new PropertyChangedEventArgs("CB3Checked"));
}
}
public bool CB3Checked
{
get { return _cb1Checked && _cb2Checked; }
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
After setting CB1Checked or CB2Checked, you need to raise the event that CB3Checked has also changed.
Your XAML would look something like (and this is from memory...):
<CheckBox IsChecked={Binding CB1Checked}" />
<CheckBox IsChecked={Binding CB2Checked}" />
<CheckBox IsChecked={Binding CB3Checked, Mode=OneWay}" />
As #wkl points out in the comments, the third checkbox should be a one-way binding since the value can't be set.
Some MVVM frameworks might make this a little easier for you, I've not used any to be able to recommend though.
You can do it like this for a single checkbox:
<CheckBox x:Name="cb3" IsChecked="{Binding Path=IsChecked, ElementName=cb2}" />
I assume the other checkbox is called cb2.
For multiple checkboxes I recommend a Binding in you DataContext.
<CheckBox IsChecked="{Binding Path=CB_1_Checked}" Content="CheckBox 1" />
public bool CB_1_Checked
{
get { return _cb_1_checked; }
set
{
_cb_1_checked = value;
OnPropertyChanged();
//Notify that CB_3_Checked may have changed:
OnPropertyChanged("CB_3_Checked");
}
}
Do this for CB1 and CB2.
Add this for CB3
//Will return 'true' when both are checked (but lacks OnPropertyChanged !)
public bool CB_3_Checked => (CB_1_Checked && CB_2_Checked);
Or with a little more options:
private bool _cb_3_checked;
public bool CB_3_Checked
{
get
{
if(CB_1_Checked && CB_2_Checked)
{
_cb_3_checked = true;
}
return _cb_3_checked;
}
set
{
_cb_3_checked = value;
OnPropertyChanged();
}
}
Read more about Bindings here.

Value of the property does not change when the textbox is cleared

I have a ViewModel Called HaemogramViewModel
Here is code:
public class HaemogramViewModel : INotifyPropertyChanged
{
public HaemogramViewModel()
{
}
public Haemogram CurrentHaemogramReport
{
get
{
return MainWindowViewModel.cHaemogram;
}
set
{
MainWindowViewModel.cHaemogram = value;
OnPropertyChanged("CurrentHaemogramReport");
}
}
protected virtual void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
In my MainWindowViewModel Calss:
class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
cHaemogram = new Haemogram();
}
public static Haemogram cHaemogram { get; set; }
private void SaveChanges(object obj)
{
using (Lab_Lite_Entities db = new Lab_Lite_Entities())
{
//db.Patients.Add(CurrentPatient);
if (cHaemogram != null)
{
if (cHaemogram.Haemoglobin != null)
{
db.Haemograms.Add(cHaemogram);
}
}
}
}
}
My textbox is bound to the field Haemoglobin of CurrentHaemogram Property.
When I enter some value in the textbox and then click save button then everything works fine.
Now the problem is :
When I enter some value in the textbox then I press tab and then again click on textbox and then clear the value in the textbox. Now if I click on save button then I don't get the textbox's value = null, instead I get the textbox's value = the value that I entered previously.
Try this it works
<TextBox Text="{Binding B, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>
and in you view model property should be declared as below
private double? b;
public double? B
{
get
{
return b;
}
set
{
b = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("B"));
}
}
}
In your xmal you have to set the property UpdateSourceTrigger=PropertyChanged as below
<TextBox Text="{Binding Path=Property, UpdateSourceTrigger=PropertyChanged}"/>
By defalut UpdateSourceTrigger=LostFocus, that means the property bound to the textBox will get updated once you press tab or it's focus is lost. If you set to PropertyChanged it will update the property for every char change in the textBox

I have bind numbers to CombBox. I want change value comboBox and textBox changed value

I want change number from ComboBox and change value in TextBox.
(For example I have number =2 and content at "lblblblb" ofc. this is in ObservableCollection<string>, so I to call ContentWithListView[SelectNumberStep])
ReadPage.xaml
<TextBox HorizontalAlignment="Left" Margin="580,154,0,0"
TextWrapping="Wrap" Text="{Binding ContentWithListView[SelectNumberStep],Mode=TwoWay}"
VerticalAlignment="Top" Width="725" Height="82"/>
<ComboBox HorizontalAlignment="Left" Margin="440,154,0,0"
ItemsSource="{Binding NumberStep,Mode=TwoWay}"
SelectedItem="{Binding SelectNumberStep,Mode=TwoWay}"
VerticalAlignment="Top" Width="95" Height="77" />
How I change content in TextBox from CombBox numbers?
ReadViewModel.cs
private ObservableCollection<string> contentWithListView;
public ObservableCollection<string> ContentWithListView
{
get
{
return this.contentWithListView;
}
set
{
this.contentWithListView = value;
}
}
private ObservableCollection<int> stepNumber;
public ObservableCollection<int> NumberStep
{
get
{
return this.stepNumber;
}
set
{
this.stepNumber = value;
}
}
private int selectNumberStep;
public int SelectNumberStep
{
get
{
return this.selectNumberStep;
}
set
{
this.selectNumberStep = value;
}
}
previous answer doesn't integrate the fact he textbox content have to be in TwoWays so, in such scenario, you could consolidate your properties with the INotifyPropertyChanged interface like that:
Xaml part
<StackPanel d:DataContext="{d:DesignInstance Type=classes:StackOverFlowX }">
<TextBox Text="{Binding Content, Mode=TwoWay}"/>
<ComboBox ItemsSource="{Binding NumberStep, Mode=TwoWay}"
SelectedItem="{Binding SelectNumberStep,Mode=TwoWay}"/>
</StackPanel>
Class
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class StackOverFlowX : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public StackOverFlowX()
{
}
private ObservableCollection<string> contentWithListView;
public ObservableCollection<string> ContentWithListView
{
get
{
return this.contentWithListView;
}
set
{
this.contentWithListView = value;
OnPropertyChanged();
}
}
private ObservableCollection<int> stepNumber;
public ObservableCollection<int> NumberStep
{
get
{
return this.stepNumber;
}
set
{
this.stepNumber = value;
OnPropertyChanged();
}
}
private int selectNumberStep;
public int SelectNumberStep
{
get
{
return this.selectNumberStep;
}
set
{
this.selectNumberStep = value;
OnPropertyChanged();
OnPropertyChanged("Content");
}
}
private string _content;
public string Content
{
get
{
return contentWithListView[this.SelectNumberStep];
}
set
{
this._content = value;
if (contentWithListView.IndexOf(value) > -1)
{
SelectNumberStep = contentWithListView.IndexOf(value);
OnPropertyChanged("SelectNumberStep");
}
OnPropertyChanged();
}
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I would change your view model code around, so that the text box binds to a scalar string value which is updated on the SelectNumberStep change:
public string Content
{
get
{
// bounds checking here..
return contentWithListView[this.SelectNumberStep];
}
}
public int SelectNumberStep
{
get
{
return this.selectNumberStep;
}
set
{
this.selectNumberStep = value;
this.NotifyOfPropertyChange(() => this.SelectNumberStep);
this.NotifyOfPropertyChange(() => this.Content);
}
}
<TextBox Text="{Binding Content}" ... />

How can i set binding to childproperty from App.xaml

I have a problem with my Binding to a ListBox Control.
Actually i have a Property in App.xaml.cs :
public partial class App : Application, INotifyPropertyChanged
{
ObservableCollection<Panier> _panier = new ObservableCollection<Panier>();
public ObservableCollection<Panier> PanierProperty
{
get { return _panier; }
set
{
if (this._panier != value)
{
this._panier = value;
NotifyPropertyChanged("PanierProperty");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
this property have a child properties in the "Panier class" here:
public class Panier : INotifyPropertyChanged
{
private string _nom;
private string _category;
private int _prix;
public string Nom
{
get { return _nom; }
set
{
if (this._nom != value)
{
this._nom = value;
NotifyPropertyChanged("Nom");
}
}
}
public string Category
{
get { return _category; }
set
{
if (this._category != value)
{
this._category = value;
NotifyPropertyChanged("Category");
}
}
}
public int Prix
{
get { return _prix; }
set
{
if (this._prix != value)
{
this._prix = value;
NotifyPropertyChanged("Prix");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
and in my MainWindow.xaml page i have my ListBox bound to PanierProperty(parent property) :
<telerik:RadListBox x:Name="PanierLB" Grid.Row="1" Height="200" Width="350" Margin="0 300 0 0"
ItemsSource="{Binding PanierProperty, Source={x:Static Application.Current}}"
DisplayMemberPath="{Binding Path=PanierProperty.Nom, Source={x:Static Application.Current}}">
</telerik:RadListBox>
my problem is that PanierProperty is bound to my Listbox i see items in the listbox like Design.Panier
Design.Panier
Design.Panier
etc...
I dont know how to get the PanierProperty.Nom(Nom is the child property) to show on the ListBox.
Someone can help please.
In DisplayMemberPath use the name of property you want to show only:
<telerik:RadListBox
...
DisplayMemberPath="Nom"

Categories