2013-03-03 60 views
1

我想創建一個類似於Microsoft Outlook的窗口標題。有條件的XAML綁定

對於這一點,我創建了以下綁定:

<MultiBinding StringFormat="{}{0} - Message ({1})}"> 
    <Binding ElementName="txtSubject" Path="Text" /> 
    <Binding ElementName="biSendAsHtml">****</Binding> 
</MultiBinding> 

現在我想知道我怎樣才能使第二結合條件。如biSendAsHtml.IsChecked等於true顯示HTML其他顯示純文本

回答

2

我不知道你是怎麼想的sa_ddam213的答案是優雅的,它只是嚇人。像RV1987建議的那樣,轉換器是正確的方法,但是你可以變得更聰明。

創建一個轉換器,它需要一個布爾值並將其轉換爲在轉換器定義中定義的選項。

public class BoolToObjectConverter : IValueConverter 
{ 
    public object TrueValue { get; set; } 
    public object FalseValue { get; set; } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return Convert.ToBoolean(value) ? TrueValue : FalseValue; 
    } 

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

定義轉換器:

<local:BoolToObjectConverter x:Key="SendAsHtmlBoolToTextConverter" 
          TrueValue="HTML" 
          FalseValue="Plain Text"/> 

並使用它:

<MultiBinding StringFormat="{}{0} - Message ({1})}"> 
    <Binding ElementName="txtSubject" Path="Text" /> 
    <Binding ElementName="biSendAsHtml" Path="IsChecked" 
      Converter="{StaticResource SendAsHtmlBoolToTextConverter}"/> 
</MultiBinding> 

如果你願意,你甚至可以使TrueValue和FalseValue DependencyProperties支持綁定。

+1

這看起來像一個非常通用的方式。榮譽和感謝! – SeToY 2013-03-07 22:28:12

+0

稍作修改:如果您製作TrueValue和FalseValue屬性對象而不是字符串,則它更具可重用性。例如,您可以使用顏色/筆刷來根據條件改變某種顏色。 – 2013-03-10 22:16:30

+0

呵呵,我已經想到了這一點,並在我的應用程序中做到了這一點:P謝謝! – SeToY 2013-03-11 09:27:42

2

創建IValueConverter,並用它在你的第二個結合 -

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, 
          System.Globalization.CultureInfo culture) 
    { 
     return (bool)value ? "HTML" : "Your Text"; 
    } 

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

這裏去您的XAML -

<MultiBinding StringFormat="{}{0} - Message ({1})}"> 
    <Binding ElementName="txtSubject" Path="Text" /> 
    <Binding ElementName="biSendAsHtml" Path="IsChecked" 
      Converter="{StaticResource Myconverter}"/> 
</MultiBinding>