0

我有一个文本框,它与复选框一起添加到一个窗口中。我已经设法将 TextBox 绑定到OrderCheckedListItem 处理程序的属性,因此当进行更改时,它会正确绑定并更新。

我遇到的问题是我无法使用起始值对其进行初始化。我的构造函数如下

public partial class OwnerSettingWindow : Window
{

public ObservableCollection<CheckedListItem<Owner>> Owners { get; set; }

public class Owner
{    
    public String OwnerName { get; set; }
    public String OwnerOrder { get; set; }

}

public OwnerSettingWindow()
{
    InitializeComponent();

    Owners = new ObservableCollection<CheckedListItem<Owner>>();

    string testString = @"Item1,true,1:Item2,true,2:Item3,false,24"; ;
    string[] splitOwners = testString.Split(':');

    foreach (string item in splitOwners)
    {
        string[] spOwnerSetting = item.Split(',');

        bool bchecked = bool.Parse(spOwnerSetting[1].ToString());
        string norder = spOwnerSetting[2].ToString();
        Owners.Add(new CheckedListItem<Owner>(new Owner() { OwnerName = spOwnerSetting[0].ToString(), OwnerOrder = norder }, 
            isChecked: bchecked));
    }

    DataContext = this;
}


public class CheckedListItem<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked;
    private T item;
    private string order;

    public CheckedListItem()
    { }

    public CheckedListItem(T item, bool isChecked = false)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
        }
    }


    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }

    public string Order
    {
        get { return order; }
        set
        {
            order = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Order"));
        }
    }
}
}

以下行未按预期工作

    Owners.Add(new CheckedListItem<Owner>(new Owner() { OwnerName = 
spOwnerSetting[0].ToString(), OwnerOrder = norder }, 
                isChecked: bchecked));

OwnerOrder = norder打开窗口时不显示。我在 XAML 中的 TextBox 绑定很简单<TextBox Text ="{Binding Order}"/>

我也尝试了以下但没有成功 Owners.Add(new CheckedListItem<Owner>(new Owner() { OwnerName = spOwnerSetting[0].ToString() }, isChecked: bchecked, order: norder));

有任何想法吗?

4

1 回答 1

2

CheckedListItem 中的 Order 属性从不初始化。你可以添加一个新的ctor

public CheckedListItem(T item, string nrorder, bool isChecked = false)
{
   this.item = item;
   this.isChecked = isChecked;
   this.order = nrorder;
}

并更改您的添加方法

Owners.Add(new CheckedListItem<Owner>(new Owner() { OwnerName = spOwnerSetting[0].ToString(), OwnerOrder = norder }, norder, isChecked: bchecked));

在我的测试应用程序中现在正在工作。

于 2012-10-10T10:42:52.730 回答