2008-09-24 111 views
12

我想將一個常量值添加到傳入的綁定整數。事實上,我有幾個地方我想要綁定到相同的源值,但添加不同的常量。因此,理想的解決辦法是這樣的......簡單的算術運算WPF DataBinding?

<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/> 
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/> 
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/> 

(注:這是爲了顯示這個想法的例子,我實際的結合情況是不是一個TextBox的帆布財產但這給出了這個概念。更清楚地)

目前我唯一能想到的解決方案是公開許多不同的源屬性,每個屬性都增加了一個不同的常量到相同的內部值。所以我可以做這樣的事情...

<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/> 
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/> 
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/> 

但這是非常嚴峻的,因爲在未來我可能需要不斷添加新屬性的新常量。另外,如果我需要更改附加值,則需要更改源對象,這非常不錯。

必須有比這更通用的方式嗎?任何WPF專家有任何想法?

回答

6

我相信你可以用價值轉換器來做到這一點。這是一個blog entry,它將一個參數傳遞給xaml中的值轉換器。 this blog給出了實現一個值轉換器的一些細節。

+0

值轉換器可以採取參數似乎事實上用它就像在這裏解決問題的一個好方法。感謝您的意見。 – 2008-09-24 05:51:51

0

我從來沒有使用WPF,但我有一個可能的解決方案。

你的綁定路徑能映射到一個Map嗎?如果是這樣,它應該能夠接受一個參數(關鍵)。您需要創建一個實現Map接口的類,但實際上只是返回初始化添加到鍵的「Map」的基本值。

public Integer get(Integer key) { return baseInt + key; } // or some such 

沒有一定的能力從標記中傳遞數字,我沒有看到如何讓它從原始值返回不同的增量。

4

使用值轉換器是一個很好的解決方案,因爲它允許您修改源值,因爲它綁定到UI。

我在幾個地方使用了以下內容。

public class AddValueConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     object result = value; 
     int parameterValue; 

     if (value != null && targetType == typeof(Int32) && 
      int.TryParse((string)parameter, 
      NumberStyles.Integer, culture, out parameterValue)) 
     { 
      result = (int)value + (int)parameterValue; 
     } 

     return result; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

<Setter Property="Grid.ColumnSpan" 
     Value="{Binding 
        Path=ColumnDefinitions.Count, 
        RelativeSource={RelativeSource AncestorType=Grid}, 
        Converter={StaticResource addValueConverter}, 
        ConverterParameter=1}" 
    /> 
18

我使用的是MathConverter,我創建做所有簡單arithmatic操作有。該轉換器的代碼here,它可以這樣使用:

<TextBox Canvas.Top="{Binding SomeValue, 
      Converter={StaticResource MathConverter}, 
      [email protected]+5}" /> 

,你甚至可以用更先進的arithmatic操作,如

Width="{Binding ElementName=RootWindow, Path=ActualWidth, 
       Converter={StaticResource MathConverter}, 
       ConverterParameter=((@VALUE-200)*.3)}" 
+0

不錯的轉換器,但是如果值是一個負數,就會中斷。一個快速的解決方法是使用一些其他的符號,而不是「 - 」,並分別修改MathConverter代碼中的操作數列表。當然,真正的解決方案需要在解析時添加更多的邏輯。 – 2014-06-25 13:33:10