2013-07-04 86 views
0

我有一個TextBlock名爲Price。我有一個DataTrigger工作。WPF textblock text和DataTrigger

<DataTrigger Binding="{common:ComparisonBinding DataContext.Discount,GT,0}" Value="{x:Null}"> 
    <DataTrigger.Setters> 
     <Setter Property="Text" TargetName="price"> 
      <Setter.Value> 
       <Run>Value1</Run> 
       <Run>Value2</Run> 
      </Setter.Value>     
     </Setter> 
    </DataTrigger.Setters> 
</DataTrigger> 

因此,這意味着,如果Discount is > 0它應該Text.However這並不裏面工作運行顯示這一點。我需要綁定,因爲我需要不同的文本樣式。

回答

2

正如xaml和@BasBrekelmans中的錯誤所述,您嘗試將Run元素分配給期望值爲string的屬性。

根據您的要求,只需使用MultiBindingStringFormat將您的界限值格式化爲所需格式。

類似:

<DataTrigger Binding="{common:ComparisonBinding DataContext.Discount,GT,0}" 
       Value="{x:Null}"> 
    <Setter TargetName="price" 
      Property="Text"> 
     <Setter.Value> 
     <MultiBinding StringFormat="Some Custom Formatted Text Value1: {0} and Value2: {1}"> 
      <Binding Path="BindingValue1" /> 
      <Binding Path="BindingValue2" /> 
     </MultiBinding> 
     </Setter.Value> 
    </Setter> 
</DataTrigger> 

如果它的TextBlock您想與在線綁定的葉來調整你最好比單一TextBlock更好元素修改控件的模板的視覺樣式允許。

但是你可以通過使用一個轉換器和應用使用一個解決您的DataTrigger.SetterTextBlock.Tag

這樣說:

public class TextBlockInlineFormatConverter : IMultiValueConverter { 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { 
    if (values.Length < 3) 
     return null; 
    TextBlock textblock = values[0] as TextBlock; 
    if (textblock == null) 
     return null; 
    textblock.ClearValue(TextBlock.TextProperty); 
    textblock.Inlines.Add(new Run("Some text ") { Foreground = Brushes.Tomato }); 
    textblock.Inlines.Add(new Run(values[1].ToString()) { Foreground = Brushes.Blue }); 
    textblock.Inlines.Add(new Run(" and Some other text ") { Foreground = Brushes.Tomato }); 
    textblock.Inlines.Add(new Run(values[2].ToString()) { Foreground = Brushes.Blue, FontWeight = FontWeights.Bold }); 
    return textblock.Tag; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { 
    throw new NotImplementedException(); 
    } 
} 

與用法:

<DataTrigger Binding="{common:ComparisonBinding DataContext.Discount,GT,0}" 
       Value="{x:Null}"> 
    <!-- Note the setter is on Tag and not Text since we modify the Text using Inlines within the converter --> 
    <Setter TargetName="price" 
      Property="Tag"> 
     <Setter.Value> 
     <MultiBinding Converter="{StaticResource TextBlockInlineFormatConverter}" 
         Mode="OneWay"> 
      <Binding Path="." 
        RelativeSource="{RelativeSource Self}" /> 
      <Binding Path="BindingValue1" /> 
      <Binding Path="BindingValue2" /> 
     </MultiBinding> 
     </Setter.Value> 
    </Setter> 
</DataTrigger> 

使用只有在限制修改控件模板tbh的情況下才能解決此問題。

+0

這真的很聰明老兄:)謝謝。但是,由於時間壓力,我添加了第二個文本塊與空文本和觸發器我改變它的文本。我不知道哪個更有效,但。 – GorillaApe

1

收集的Run項目不能應用於Text屬性,該屬性是一個字符串。正確的屬性是Inlines

不幸的是,這個屬性沒有setter,應該有不同的方法來解決這個問題。 ContentControl與兩個TextBlockStackPanel中。