【问题标题】:Binding MVVM CheckBox inside a Listbox在列表框中绑定 MVVM CheckBox
【发布时间】:2025-12-29 02:15:11
【问题描述】:

我正在尝试在我的应用程序 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>

我的视图模型

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;

但是没用

【问题讨论】:

    标签: c# xaml windows-phone-8 mvvm listbox


    【解决方案1】:

    实现 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 属性,而不是直接添加到复选框

    这肯定会对你有所帮助..

    阅读此https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs.110%29.aspx

    【讨论】:

    • 它没有改变任何东西,但感谢 INotifyPropertyChanged :)