我有一个TextBox,它会被添加到一个Window旁边的Checkbox中。我已设法将TextBox绑定到CheckedListItem处理程序的属性Order
,因此当进行更改时,它会正确绑定并更新。
我遇到的问题是我无法用起始值初始化它。我的构造函数如下
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));
有什么想法吗?
答案 0 :(得分: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));
在我的测试应用程序中现在正在运行。