-
使用数据绑定配合IValueConverter(值转换器)
创建一个自定义转换器,该转换器接收两个输入值,并根据他们是否相等返回相应的输出值。然后将这个转换器应用到第三个控件的属性上
1 public class EqualityToTextConverter : IValueConverter 2 { 3 public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 4 { 5 string value1 = (string)values[0]; 6 string value2 = (string)values[1]; 7 8 return value1 == value2 ? "Equal" : "Not Equal"; // 根据需要返回不同的文本 9 } 10 11 public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 12 { 13 throw new NotSupportedException("EqualityToTextConverter只支持单向转换"); 14 } 15 }
在XAML中使用MultiBinding:
1 <Window.Resources> 2 <local:EqualityToTextConverter x:Key="EqualityConverter"/> 3 </Window.Resources> 4 5 <!-- 假设这两个依赖属性都在同一个ViewModel中 --> 6 <Grid DataContext="{Binding RelativeSource={RelativeSource Self}}"> 7 <TextBox Text="{Binding Property1}" /> 8 <TextBox Text="{Binding Property2}" /> 9 10 <!-- 第三个TextBox --> 11 <TextBox> 12 <TextBox.Text> 13 <MultiBinding Converter="{StaticResource EqualityConverter}"> 14 <Binding Path="Property1" /> 15 <Binding Path="Property2" /> 16 </MultiBinding> 17 </TextBox.Text> 18 </TextBox> 19 </Grid>
使用命令或事件触发逻辑: 在ViewModel中创建一个命令,当两个属性值改变时执行此命令,命令内部比较两个属性并更新第三个TextBox的Text属性。
1 public class MyViewModel : ViewModelBase 2 { 3 private string property1; 4 public string Property1 5 { 6 get { return property1; } 7 set 8 { 9 if (property1 != value) 10 { 11 property1 = value; 12 RaisePropertyChanged(nameof(Property1)); 13 CheckEquality(); 14 } 15 } 16 } 17 18 private string property2; 19 public string Property2 20 { 21 get { return property2; } 22 set 23 { 24 if (property2 != value) 25 { 26 property2 = value; 27 RaisePropertyChanged(nameof(Property2)); 28 CheckEquality(); 29 } 30 } 31 } 32 33 private void CheckEquality() 34 { 35 if (Property1 != Property2) 36 { 37 ThirdProperty = "Not Equal"; 38 } 39 else 40 { 41 ThirdProperty = "Equal"; 42 } 43 } 44 45 private string thirdProperty; 46 public string ThirdProperty 47 { 48 get { return thirdProperty; } 49 set 50 { 51 if (thirdProperty != value) 52 { 53 thirdProperty = value; 54 RaisePropertyChanged(nameof(ThirdProperty)); 55 } 56 } 57 } 58 } 59 60 <!-- XAML --> 61 <TextBox Text="{Binding Property1}" /> 62 <TextBox Text="{Binding Property2}" /> 63 <TextBox Text="{Binding ThirdProperty}" />
标签:控件,return,string,object,value,MvvmLight,public,属性 From: https://www.cnblogs.com/davisdabing/p/18081746