根据我对您的问题的理解,您正试图找到一种方法来根据您的视图模型的一个属性的值来设置Value
您的。DataTrigger
所以在这里我有一个解决方案。
这是视图模型
public class ViewModel : INotifyPropertyChanged
{
private string _text;
private string _candidateValue;
public string Text
{
get
{
return this._text;
}
set
{
this._text = value;
if (null != PropertyChanged)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
public string CandidateValue
{
get
{
return this._candidateValue;
}
set
{
this._candidateValue = value;
if (null != PropertyChanged)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
并且您在 DataTrigger 的绑定中需要一个 IValueConverter
public class ValueConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty CandidateValueProperty = DependencyProperty.Register("CandidateValue", typeof(string), typeof(ValueConverter));
public string CandidateValue
{
get { return (string)GetValue(CandidateValueProperty); }
set { SetValue(CandidateValueProperty, value); }
}
public ValueConverter()
: base()
{
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (null != value)
{
if (value.ToString() == this.CandidateValue)
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
而且xaml非常简单
<TextBox x:Name="TextBox" Text="{Binding Text,UpdateSourceTrigger=PropertyChanged}">
</TextBox>
您需要在后面的代码中创建数据触发器。
public MainWindow()
{
InitializeComponent();
//The view model object
ViewModel vm = new ViewModel();
vm.CandidateValue = "1";
this.DataContext = vm;
//create data trigger object for TextBox
DataTrigger d = new DataTrigger();
//create binding object for data trigger
Binding b = new Binding("Text");
ValueConverter c = new ValueConverter();
b.Converter = c;
//create binding object for ValueConverter.CandidateValueProperty
Binding convertBinding = new Binding("CandidateValue");
convertBinding.Source = vm;
BindingOperations.SetBinding(c, ValueConverter.CandidateValueProperty, convertBinding);
d.Binding = b;
d.Value = true;
Setter s = new Setter(TextBox.ForegroundProperty, Brushes.Red);
d.Setters.Add(s);
Style st = new Style(typeof(TextBox));
st.Triggers.Add(d);
this.TextBox.Style = st;
}
这里的诀窍是ValueConverter
有一个名为CandidateValueProperty
. 并且此属性绑定到CandidateValue
视图模型。因此,当输入值等于视图模型的 CandidateValue 时,TextBox 的前景将是红色的。