2013-02-27 51 views
0

我想知道是否有辦法將一個元素的屬性綁定到另一個元素,但修改其中的數據。例如,我可以將文本塊的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

回答

1

是的,通過實施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

0

您可以使用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>