在WPF中将控件绑定到集合/数组中的单个值 [英] Bind a control to a single value in a collection/array in WPF

查看:850
本文介绍了在WPF中将控件绑定到集合/数组中的单个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,我有一个bool集合吗?值,我想以编程方式将这些值绑定到单独的复选框。我希望绑定是TwoWay,以便在代码中更改集合中单个项目的值会更新复选框,反之亦然。

In WPF I have a collection of bool? values and I want to bind each of these to a separate checkbox programmatically. I want the bindings to be TwoWay so that changing the value of the individual item in the collection in code updates the check box and vice versa.

我花了很长时间尝试弄清楚该怎么做,我完全陷入了困境。使用以下代码,复选框仅在加载窗口时才获得正确的值,仅此而已。更改复选框甚至不会更新集合中的值。 (更新:这似乎是.NET4中的错误,因为该集合确实在相同的.NET3.5项目中进行了更新。更新:Microsoft已经确认该错误,并将在.NET4版本中修复。)

I have spent ages trying to figure out how to do this and I am completely stuck. With the following code the checkbox only gets the right value when the window is loaded and that's it. Changing the check box doesn't even update the value in the collection. (UPDATE: this appears to be a bug in .NET4 as the collection does get updated in an identical .NET3.5 project. UPDATE: Microsoft have confirmed the bug and that it will be fixed in the .NET4 release.)

在此先感谢您的帮助!

C#:

namespace MyNamespace
{
    public partial class MyWindow : Window, INotifyPropertyChanged
    {
        public MyWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

        public List<bool?> myCollection = new List<bool?>
            { true, false, true, false, true, false };

        public List<bool?> MyCollection
        {
            get { return myCollection; }
            set { myCollection = value; }
        }
    }
}

XAML:

<CheckBox IsChecked="{Binding Path=MyCollection[0], Mode=TwoWay}">


推荐答案

这里需要更改一些内容这个工作。首先,您需要将布尔值包装在实现INotifyPropertyChanged接口的对象中,以便获取您要查找的更改通知。当前,您正在绑定到不实现该接口的集合中的布尔值。为此,您可以创建一个包装类,如下所示:

There are a few things that need changing here to get this to work. Firstly you'll need to wrap your boolean value in an object that implements the INotifyPropertyChanged interface in order to get the change notification that you are looking for. Currently you are binding to boolean values in your collection which do not implement the interface. To do this you could create a wrapper class like so :

  public class Wrapper: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private bool val = false;

        public bool Val
        {
            get { return val; }
            set
            {
                val = value;
                this.OnPropertyChanged("Val");
            }
        }

        public Wrapper(bool val)
        {
            this.val = val;
        }

    }

然后您需要创建这些对象以表单的形式出现,而不是布尔值列表。您可能还希望使用可观察的集合而不是列表,以便发送有关添加和删除的项目的通知。如下所示:

You'll then want to create these objects in your form instead of a list of booleans. You may also want to use an observable collection instead of a list so that notification of items being added and removed are sent. This is shown below:

public Window1()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    private ObservableCollection<Wrapper> myCollection = new ObservableCollection<Wrapper>()
        {new Wrapper(true), new Wrapper(false), new Wrapper(true)};


    public ObservableCollection<Wrapper> MyCollection
    {
        get { return myCollection; }
    }

接下来要做的是在您的计算机中显示复选框列表ui。为此,WPF提供了项控件。 ListBox是一个项控件,因此我们可以以此为起点。将列表框的itemssource设置为MyCollection。然后,我们需要定义如何在列表框中显示每个包装器对象,这可以通过在Windows资源中创建的数据模板来完成。如下所示:

The next thing to do is to display a list of check boxes in your ui. To do this WPF provides itemscontrols. ListBox is an itemscontrol so we can use this as a starting point. Set the itemssource of a listbox to be MyCollection. We then need to define how each Wrapper object is going to be displayed in the list box and this can be done with a datatemplate which is created in the windows resources. This is shown below :

<Window.Resources>
    <DataTemplate x:Key="myCollectionItems">
        <CheckBox IsChecked="{Binding Path=Val, Mode=TwoWay}"></CheckBox>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Path=MyCollection}" ItemTemplate="{StaticResource myCollectionItems}"></ListBox>
</Grid>

这应该使您开始并运行一个简单的复选框演示,该复选框具有绑定到列表的值布尔值。

This should get you up and running with a simple demo of checkboxes that have values bound to a list of booleans.

这篇关于在WPF中将控件绑定到集合/数组中的单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆