我试图在我的应用程序Windows Phone中使用模式MVVM。但我有一个问题是绑定一个列表框内的CheckBox。
这是我的.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>
我的ViewModel
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;
但它没有工作
答案 0 :(得分:0)
实施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>
您需要为Listbox添加ItemsSource属性,而不是直接添加到复选框
这肯定会帮助你..