【发布时间】:2012-03-12 12:53:21
【问题描述】:
我想实现,当文本框的值改变时,我的添加按钮变得可用。
我将文本框与 viewModel 绑定:
<TextBox Name="nameTbx" Text="{Binding Path=NewNode.Name, Mode=TwoWay}" />
我的按钮:
<Button Content="Add" Command="{Binding Path=AddNewNodeProperty}"/>
在后面的 XAML 代码中,我将 DataContext 设置为我的 ViewModel。 ViewModel 看起来像:
/* code*/
private Node _newNode = new Node();
public Node NewNode
{
get
{
return _newNode;
}
set
{
_newNode = value;
OnPropertyChanged("NewNode");
}
}
private AddNode _addNewNodeProperty;
public AddNode AddNewNodeProperty
{
get
{
return _addNewNodeProperty;
}
}
在构造函数中我初始化 _addNewNodeProperty
this._addNewNodeProperty = new AddNode(this);
这是我的 AddNode 类:
public class AddNode : ICommand
{
private ServiceMapViewModel viewModel;
public AddNode(ServiceMapViewModel viewModel)
{
this.viewModel = viewModel;
this.viewModel.PropertyChanged += (s, e) =>
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
};
}
public bool CanExecute(object parameter)
{
bool b = !string.IsNullOrWhiteSpace(this.viewModel.NewNode.Name);
return b;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
this.viewModel.AddNewNode();
}
}
最后是我的 Node 类:
public class Node
{
public string Name { get; set; }
public bool? IsChecked { get; set; }
public Group Group { get; set; }
public Category Category { get; set; }
public string Metadata { get; set; }
public List<string> Children = new List<string>();
public List<string> Parents = new List<string>();
}
问题是当我更改我的文本框文本时,NewNode 正在为我获取值,但它应该设置。
Tnx 进阶!
编辑 让我补充一点:
I also have a datagrid on the screen and when Selected Item is changed, my Add butom become available.
所选项目:
<DataGrid Name="nodeDataGrid" ItemsSource="{Binding Path=MyServiceMap.Nodes}"
Background="Silver" Margin="0,34,10,10" IsReadOnly="True" SelectedItem="{Binding Path=SelectedNode}" >
和虚拟机:
private Node _selectedNode = new Node();
public Node SelectedNode
{
get
{
return _selectedNode;
}
set
{
_selectedNode = value;
OnPropertyChanged("SelectedNode");
}
}
【问题讨论】: