Jac*_*ter 56
你在找MultiBinding.
你的XAML遗嘱看起来像这样:
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myConverter}">
<Binding Path="myFirst.Value" />
<Binding Path="mySecond.Value" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
随着合理的替代品myConverter,myFirst.Value和mySecond.Value.
Don*_*lle 35
创建一个实现IMultiValueConverter的转换器.它可能看起来像这样:
class AverageConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int total = 0;
int number = 0;
foreach (object o in values)
{
int i;
bool parsed = int.TryParse(o.ToString(), out i);
if (parsed)
{
total += i;
number++;
}
}
if (number == 0) return 0;
return (total/number).ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
多值转换器接收一个对象数组,每个绑定对应一个对象数组.您可以根据需要处理这些,具体取决于您是打算使用double还是int或者其他什么.
如果两个文本框是数据绑定,则可以在文本块的多重绑定中使用相同的绑定(记住在属性更改时通知以便更新平均值),或者可以通过按ElementName引用文本框来获取文本值.
<TextBox Text="{Binding Value1}" x:Name="TextBox1" />
<TextBox Text="{Binding Value2}" x:Name="TextBox2" />
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource AverageConverter}">
<Binding ElementName="TextBox1" Path="Text" />
<Binding ElementName="TextBox2" Path="Text" />
<!-- OR -->
<!-- <Binding Path="Value1" /> -->
<!-- <Binding Path="Value2" /> -->
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48842 次 |
| 最近记录: |