【发布时间】:2015-12-10 04:45:54
【问题描述】:
我有一个名为 Document
的类public class Document : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string oldId;
public string OldId
{
get { return oldId; }
set { id = value; }
}
private string id;
public string Id
{
get { return id; }
set {
id = value;
NotifyPropertyChanged("HasChanged");
}
}
private string path;
public string Path
{
get { return path; }
set { path = value; }
}
public bool HasChanged
{
get { return id != oldId; }
}
public Document(string id, string path)
{
this.id = id;
this.oldId = id;
this.path = path;
}
}
我在我的 WPF 代码后面有一个 Documents 列表,items 是我表单中的一个 ItemsControl。
AddItem("a", "b");
AddItem("b", "b");
AddItem("c", "b");
AddItem("d", "b");
...
private void AddItem(string key, string value)
{
items.Items.Add(new Document(key, value));
}
我的 WPF 如下所示:
<ItemsControl x:Name="items" AlternationCount="100">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="8*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox
Text="{Binding Id}"
PreviewKeyDown="TextBox_PreviewKeyDown"></TextBox>
<Button
Grid.Column="1"
IsEnabled="{Binding HasChanged}"
Content="Ok"
Click="ButtonOk_Click"></Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如您所料,当 tb 中的文本与原始文本不同时,我想启用 Button。
问题是在我更改其中一个文本框中的文本后,按钮无法启用。
如果我点击按钮,它会变为启用。
如果我再次单击它,它会执行 OnClick。
有什么改变,按钮在按键时更新?
请记住,我使用 ItemControl 即时生成按钮,因此无法通过其名称从代码隐藏更新它。
我不使用 ViewModel,也不想添加,因为这个项目太小,无法使用任何基于 ViewModel 的设计模式。
【问题讨论】: