第二种方法是要走的路。在您的 viewmodel 中,添加 ICommand DoOnTextChanged 和依赖属性 BackgroundColor。
- 使用行为将
DoOnTextChanged 命令与TextBox1 的TextChanged 事件绑定
- 使用转换器将
BackgroundColor属性绑定到TextBox2的背景。
- 在
DoOnTextChanged的Execute函数中,修改BackgroundColor的属性即可。
如果您使用的是 MVVMLight,绑定到 ICommand 很容易。首先添加这两个命名空间xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 和xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform" 并执行以下操作:
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged" >
<cmd:EventToCommand Command="{Binding DoOnTextChanged}" PassEventArgsToCommand="False" >
</cmd:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
更新
由于 OP 使用的是普通 wpf/Xaml,我正在使用普通 wpf 的实现来更新我的答案。
在你的项目中添加以下两个帮助类:
public class ExecuteCommand : TriggerAction<DependencyObject>
{
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExecuteCommand));
public ICommand Command
{
get
{
return GetValue(CommandProperty) as ICommand;
}
set
{
SetValue(CommandProperty, value);
}
}
protected override void Invoke(object parameter)
{
if (Command != null)
{
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
}
public class EventCommand : ICommand
{
private Action<object> func;
public EventCommand(Action<object> func)
{
this.func = func;
}
public bool CanExecute(object parameter)
{
//Use your logic here when required
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (func != null)
{
func(parameter);
}
}
}
在您的 ViewModel 中,实现 INotifyPropertyChanged 并添加以下 ICommand 和 Background 属性。
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel(IDataService dataService)
{
BackColor = Brushes.Aqua;
DoOnTextChanged = new EventCommand((obj => BackColor = BackColor == Brushes.BurlyWood ? Brushes.Chartreuse : Brushes.BurlyWood));
}
public ICommand DoOnTextChanged { get; set; }
private Brush backColor;
public Brush BackColor
{
get
{
return backColor;
}
set
{
backColor = value;
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("BackColor"));
}
}
}
}
最后,在您的 ViewName.xaml 文件中,添加此命名空间 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"。您可能需要添加对 System.Windows.Interactivity 的引用。然后添加以下内容以将按钮事件绑定到命令:
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged" >
<local:ExecuteCommand Command="{Binding DoOnTextChanged}"></local:ExecuteCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<TextBox Background="{Binding BackColor}"></TextBox>
虽然完成一些简单的事情需要很多代码,但在某些情况下它确实很有帮助。最好学习所有方法并使用最适合您需要的方法。