我正在尝试在我的应用程序Windows Phone中使用模式MVVM。但是我对绑定列表框中的复选框有问题。
这是我的.xaml
<ListBox x:Name="LstbTagsFavoris" SelectionChanged="favoris_SelectionChanged" Margin="10,10,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Foreground="#555" Background="Red" Loaded="CheckBox_Loaded" Unchecked="CheckBox_Unchecked" Checked="CheckBox_Checked" Content="{Binding Categories}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的视图模型
public class CategorieViewModel
{
private List<string> _Categories = new List<string>();
public List<string> Categories
{
get
{
return _Categories;
}
set
{
_Categories = value;
}
}
public void GetCategories()
{
Categories = GlobalVar._GlobalItem.SelectMany(a => a.tags)
.OrderBy(t => t)
.Distinct()
.ToList();
}
在我的 xaml 中.cs
: CategorieViewModel c = new CategorieViewModel();
c.GetCategories();
this.DataContext = c;
但它没有用
Realize INotifyPropertyChanged 接口。
这样做。
public class CategorieViewModel : INotifyPropertyChanged
{
private List<string> _Categories = new List<string>();
public List<string> Categories
{
get
{
return _Categories;
}
set
{
_Categories = value;
OnPropertyChanged("Categories");
}
}
public void GetCategories()
{
Categories = GlobalVar._GlobalItem.SelectMany(a => a.tags)
.OrderBy(t => t)
.Distinct()
.ToList();
}
protected void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
在 XAML 代码中:
<ListBox x:Name="LstbTagsFavoris" ItemsSource="{Binding Categories}" SelectionChanged="favoris_SelectionChanged" Margin="10,10,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Foreground="#555" Background="Red" Loaded="CheckBox_Loaded" Unchecked="CheckBox_Unchecked" Checked="CheckBox_Checked" Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您需要为列表框添加 ItemsSource 属性,而不是直接添加到复选框
这肯定会帮助你..
阅读此 https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.110%29.aspx