2016-09-19 16 views
-2

我想第一次與我的C#代碼確定什麼顏色xaml將使文本在自定義文本框中的綁定。數據觸發器和綁定不起作用

我的C#代碼:

public class Limits 
{ 
public static bool fruitLimits(string textboxDec, ComboBox boxVariable) 
{ 
    if (string.IsNullorWhiteSpace(textboxDec) 
    {return false;} 
    else if (boxVariable.SelectedIndex == 1) 
    { 
     try 
     { int apples = Convert.ToInt32(textboxDex); 
      if (apples < 4 && apples != 0) 
      {return false;} 
      else if(apples > 50) 
      {return false;} 
      else 
      return true; 
     } 
     catch (FormatException fEx) 
     {return false;} 
     } 
     else 
     { 
      try 
      { int oranges = Convert.ToInt32(textboxDec); 
      if (oranges < 1 && oranges != 0) 
      { 
      return false;} 
      else if (oranges > 100) 
      {return false;} 
      else 
      return true; 
      } 
      catch (FormatException fEx2) 
      {return false;} 
     } 
    } 

所以現在我想結合這個方法爲XAML所以當此方法返回true,框中的文字是黑色的,當它返回false,該文本是紅色的。

<local:DigitBox x:Name="FruitNumber"> 
    <local:DigitBox.Style> 
    <Style TargetType="local:DigitBox"> 
    <Style.Triggers> 
    <DataTrigger 
    Binding="{Binding Limits.fruitLimits}" Value="False"> 
    <Setter Property="Foreground" Value="Red"/> 
    </DataTrigger> 
    </Style.Triggers> 
    </Style> 
    </local:DigitBox.Style> 
    </local:DigitBox> 

所以沒有發現錯誤,但我的自定義文本框不會改變顏色。我嘗試直接在我的c#方法中設置顏色更改,並且工作。但我正在努力遵守我一直在閱讀的內容,這些內容是保持xaml中的視覺變化。這需要約束力,但我顯然缺少/不理解關鍵的東西

+0

有時是很有幫助的讀一本書或有關技術要領* *前嘗試使用它的文章。對於WPF數據綁定,我建議閱讀MSDN上的[數據綁定概述](https://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)文章理解。 – Clemens

回答

1

你的問題是,你正試圖綁定到一個方法,而不是一個屬性。 嘗試是這樣的:

public static bool fruitLimits 
{ 
    get 
    { /*your method code here*/ } 
} 

編輯: 有沒有辦法將參數傳遞到屬性,所以如果你沒有訪問到文本框中的值,您可能需要寫一個轉換器,通過這些值。這裏的基本知識:link 您可以傳遞一個對象作爲值,另一個作爲參數傳遞。 轉換器然後處理信息並返回一個布爾值。 這裏的綁定該轉換器的應該是什麼樣子的例子:

這裏一個例子,你的結合應該是這個樣子:

   <DataTrigger Value="True"> 
        <DataTrigger.Binding> 
         <MultiBinding Converter="{StaticResource converterKey}"> 
          <Binding ElementName="boxVariable" /> 
          <Binding ElementName="textboxDec" Path="Text" /> 
         </MultiBinding> 
        </DataTrigger.Binding> 

替換「的ElementName = boxVariable」和「的ElementName = textboxDec 「用你想要傳遞的控件名稱。您可能需要在文本框綁定上添加「Path = Text」。

然後在IMultiValueConverter做這樣的事情:

public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    if (value[0].GetType().Equals(typeof(ComboBox)) && value[1].GetType().Equals(typeof(String))) 
    { 
     ComboBox boxVariable = value[0] as ComboBox; 
     string textboxDec = value[1] as String; 

     /* your method code here, returns Boolean */ 
    } 
} 
+0

謝謝我現在就試試 – JohnChris

+0

你能舉一個轉換器的例子嗎? - 它會使用我的方法fruitLimits的結果嗎?然後它將如何傳遞給屬性 – JohnChris

+0

嗨R.jauch感謝您的繼續幫助,對於DataTrigger來說,'綁定'不能在'Binding'類型的'ConverterParameter'屬性上設置。 「綁定」只能在DependencyObject的DependecyProperty上設置 – JohnChris