在xaml中更改绑定值

问题描述:

我想知道是否有办法将一个元素的属性绑定到另一个元素,但修改其中的数据。例如,我可以将文本块的FontSize绑定到窗口的width/20或类似的东西吗?我已经遇到过几次现在可能有用的区域,但总是找到解决方法(通常涉及向我的viewModel添加字段)。完全的xaml解决方案是首选。在xaml中更改绑定值

+1

使用'IValueConverter'概念:http://blogs.msdn.com/b/bencon/archive/2006/05/10/594886.aspx – MarcinJuraszek 2013-02-27 21:22:41

是的,通过实施IValueConverter

您的方案会是这个样子的转换器:

[ValueConversion(typeof(double), typeof(double))] 
public class DivideBy20Converter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var f = (double) value; 
     return f/20.0; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var f = (double)value; 
     return f * 20.0; 
    } 
} 

...而像这样的XAML:

<Window x:Class="WpfApplication3.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:wpfApplication3="clr-namespace:WpfApplication3" 
     Title="MainWindow" Height="350" Width="525" 
     x:Name="Window"> 
    <Window.Resources> 
     <wpfApplication3:DivideBy20Converter x:Key="converter"></wpfApplication3:DivideBy20Converter>   
    </Window.Resources> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition /> 
      <RowDefinition /> 
     </Grid.RowDefinitions> 
     <TextBox FontSize="{Binding ElementName=Window, Path=Width, Converter={StaticResource converter}}"></TextBox> 
    </Grid> 
</Window> 
+0

它很有趣,在问了这个问题后几个小时,我的老板在我们的培训中覆盖了它会话。感谢您的回应,我一定会利用这些。 – dragoncmd 2013-02-28 19:21:14

您可以使用IValueConverters来处理这样的逻辑。

这里是你所提到的情形的例子,可以绑定到的窗口宽度,并使用Converteř通过在ConverterParameter

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value != null && parameter != null) 
     { 
      double divisor = 0.0; 
      double _val = 0.0; 
      if (double.TryParse(value.ToString(), out _val) && double.TryParse(parameter.ToString(), out divisor)) 
      { 
       return _val/divisor; 
      } 
     } 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 
} 

XAML中提供的值来划分宽度:

<Window x:Class="WpfApplication7.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:converters="clr-namespace:WpfApplication7" 
     Title="MainWindow" Height="124" Width="464" Name="YourWindow" > 

    <Window.Resources> 
     <converters:MyConverter x:Key="MyConverter" /> 
    </Window.Resources> 

    <StackPanel> 
     <TextBlock FontSize="{Binding ElementName=YourWindow, Path=ActualWidth, Converter={StaticResource MyConverter}, ConverterParameter=20}" /> 
    </StackPanel> 
</Window>