2016-06-23 28 views
0

我正在使用MVVM設計模式製作WPF應用程序。部分應用程序是信號強度條。我們只用一個矩形的用戶控件創建了它,並創建了一個4列的網格,所以我們需要做的只是改變控件的背景或前景色。將顏色傳遞給IValueConverter

我對如何做到這一點的想法是存儲4個部分中每個部分的簡單布爾值並使用值轉換器。但是,這個控件有3個實例,每個都有不同的顏色。我如何將所需的顏色傳遞到轉換器?我知道轉換器有一個參數參數,但我一直沒有找到任何使用它的例子,所以我甚至不知道參數參數是否是我正在尋找的。

+0

如何使用轉換器?我不明白你的意思是改變控制背景來改變條。幾周前我寫了一個五段信號強度控制。如果我只是將其粘貼進去,會有幫助嗎?你可以簡單地編輯模板來改變段數或其他。 –

+0

我想它可以。我認爲轉換器只會查看該部分的布爾值,並將背景更改爲透明或不透明。 – Eric

+0

我是通過編寫GreaterThan轉換器完成的。如果輸入值大於段的「標籤」,則段具有樣式觸發器,用於將段的填充設置爲「開啓」畫筆。 –

回答

3

您的情況可能沒有最好的,你所選擇的方法來解決(這使得它很難參數段的顏色),但你的具體問題是一個很好的問題,所以我會回答它。

正如你所發現的,除了字符串之外很難傳遞任何內容到ConverterParameter。但你不必這樣做。如果你從MarkupExtension得到一個轉換器,你可以在使用它的時候分配命名和類型化的屬性,也不必將它創建爲資源(實際上,創建它作爲資源會破壞事物,因爲這將是一個共享實例並且這些屬性在創建時被初始化)。由於XAML解析器知道在類上聲明的屬性的類型,因此它將應用默認的TypeConverter對於Brush,並且您會得到與將"PapayaWhip"指定爲"Border.Background"或其他任何內容時完全相同的行爲。

這適用於任何類型,當然不只是Brush

namespace HollowEarth.Converters 
{ 
    public class BoolBrushConverter : MarkupExtension, IValueConverter 
    { 
     public Brush TrueBrush { get; set; } 
     public Brush FalseBrush { get; set; } 

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

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

     public override object ProvideValue(IServiceProvider serviceProvider) 
     { 
      return this; 
     } 
    } 
} 

用法:

<TextBox 
    xmlns:hec="clr-namespace:HollowEarth.Converters" 
    Foreground="{Binding MyFlagProp, Converter={hec:BoolBrushConverter TrueBrush=YellowGreen, FalseBrush=DodgerBlue}}" 
    /> 

你可以給BoolBrushConverter一個構造函數的參數了。

public BoolBrushConverter(Brush tb, Brush fb) 
{ 
    TrueBrush = tb; 
    FalseBrush = fb; 
} 

而在XAML ...

<TextBox 
    xmlns:hec="clr-namespace:HollowEarth.Converters" 
    Foreground="{Binding MyFlagProp, Converter={hec:BoolBrushConverter YellowGreen, DodgerBlue}}" 
    /> 

我不認爲這是一個非常適合這種情況。但是有時語義非常清晰,屬性名稱是不必要的。例如,{hec:GreaterThan 4.5}

UPDATE

這裏有一個SignalBars控制的完整實現。這對你的四個部分有五個部分,但你可以輕鬆刪除一個;這只是在模板中,並且Value屬性是double,可以按照您喜歡的任何方式(再次在模板中)對其進行細分。

SignalBars.cs

using System; 
using System.ComponentModel; 
using System.Windows.Media; 
using System.Globalization; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Markup; 

namespace HollowEarth 
{ 
    public class SignalBars : ContentControl 
    { 
     static SignalBars() 
     { 
      DefaultStyleKeyProperty.OverrideMetadata(typeof(SignalBars), new FrameworkPropertyMetadata(typeof(SignalBars))); 
     } 

     #region Value Property 
     public double Value 
     { 
      get { return (double)GetValue(ValueProperty); } 
      set { SetValue(ValueProperty, value); } 
     } 

     public static readonly DependencyProperty ValueProperty = 
      DependencyProperty.Register("Value", typeof(double), typeof(SignalBars), 
       new PropertyMetadata(0d)); 
     #endregion Value Property 

     #region InactiveBarFillBrush Property 
     [Bindable(true)] 
     [Category("Appearance")] 
     [DefaultValue("White")] 
     public Brush InactiveBarFillBrush 
     { 
      get { return (Brush)GetValue(InactiveBarFillBrushProperty); } 
      set { SetValue(InactiveBarFillBrushProperty, value); } 
     } 

     public static readonly DependencyProperty InactiveBarFillBrushProperty = 
      DependencyProperty.Register("InactiveBarFillBrush", typeof(Brush), typeof(SignalBars), 
       new FrameworkPropertyMetadata(Brushes.White)); 
     #endregion InactiveBarFillBrush Property 
    } 

    public class ComparisonConverter : MarkupExtension, IMultiValueConverter 
    { 
     public virtual object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (values.Length != 2) 
      { 
       throw new ArgumentException("Exactly two values are expected"); 
      } 

      var d1 = GetDoubleValue(values[0]); 
      var d2 = GetDoubleValue(values[1]); 

      return Compare(d1, d2); 
     } 

     /// <summary> 
     /// Overload in subclasses to create LesserThan, EqualTo, whatever. 
     /// </summary> 
     /// <param name="a"></param> 
     /// <param name="b"></param> 
     /// <returns></returns> 
     protected virtual bool Compare(double a, double b) 
     { 
      throw new NotImplementedException(); 
     } 

     protected static double GetDoubleValue(Object o) 
     { 
      if (o == null || o == DependencyProperty.UnsetValue) 
      { 
       return 0; 
      } 
      else 
      { 
       try 
       { 
        return System.Convert.ToDouble(o); 
       } 
       catch (Exception) 
       { 
        return 0; 
       } 
      } 
     } 

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

     public override object ProvideValue(IServiceProvider serviceProvider) 
     { 
      return this; 
     } 
    } 

    public class GreaterThan : ComparisonConverter 
    { 
     protected override bool Compare(double a, double b) 
     { 
      return a > b; 
     } 
    } 
} 

主題\通用。XAML

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    > 

    <Style 
     xmlns:he="clr-namespace:HollowEarth" 
     TargetType="{x:Type he:SignalBars}" 
     > 
     <!-- Foreground is the bar borders and the fill for "active" bars --> 
     <Setter Property="Foreground" Value="Black" /> 
     <Setter Property="InactiveBarFillBrush" Value="White" /> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Control"> 
        <ControlTemplate.Resources> 
         <Style TargetType="Rectangle"> 
          <Setter Property="Width" Value="4" /> 
          <Setter Property="VerticalAlignment" Value="Bottom" /> 
          <Setter Property="Stroke" Value="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}" /> 
          <Setter Property="StrokeThickness" Value="1" /> 
          <Setter Property="Fill" Value="{Binding InactiveBarFillBrush, RelativeSource={RelativeSource TemplatedParent}}" /> 
          <Setter Property="Margin" Value="0,0,1,0" /> 
          <Style.Triggers> 
           <DataTrigger Value="True"> 
            <DataTrigger.Binding> 
             <MultiBinding Converter="{he:GreaterThan}"> 
              <MultiBinding.Bindings> 
               <Binding 
                Path="Value" 
                RelativeSource="{RelativeSource TemplatedParent}" 
                /> 
               <Binding 
                Path="Tag" 
                RelativeSource="{RelativeSource Self}" 
                /> 
              </MultiBinding.Bindings> 
             </MultiBinding> 
            </DataTrigger.Binding> 
            <Setter Property="Fill" Value="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}" /> 
           </DataTrigger> 
          </Style.Triggers> 
         </Style> 
        </ControlTemplate.Resources> 
        <ContentControl 
         ContentTemplate="{Binding ContentTemplate, RelativeSource={RelativeSource TemplatedParent}}"> 
         <StackPanel 
          Orientation="Horizontal" 
          SnapsToDevicePixels="True" 
          UseLayoutRounding="True" 
          > 
          <!-- Set Tags to the minimum threshold value for turning the segment "on" --> 
          <!-- Remove one of these to make it four segments. To make them all equal height, remove Height here 
          and set a fixed height in the Rectangle Style above. --> 
          <Rectangle Height="4" Tag="0" /> 
          <Rectangle Height="6" Tag="2" /> 
          <Rectangle Height="8" Tag="4" /> 
          <Rectangle Height="10" Tag="6" /> 
          <Rectangle Height="12" Tag="8" /> 
         </StackPanel> 
        </ContentControl> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

</ResourceDictionary> 

例XAML:

<StackPanel 
    xmlns:he="clr-namespace:HollowEarth" 
    Orientation="Vertical" 
    HorizontalAlignment="Left" 
    > 
    <Slider 
     Minimum="0" 
     Maximum="10" 
     x:Name="SignalSlider" 
     Width="200" 
     SmallChange="1" 
     LargeChange="4" 
     TickFrequency="1" 
     IsSnapToTickEnabled="True" 
     /> 
    <he:SignalBars 
     HorizontalAlignment="Left" 
     Value="{Binding Value, ElementName=SignalSlider}" 
     InactiveBarFillBrush="White" 
     Foreground="DarkRed" 
     /> 
</StackPanel> 
+0

我會調查你的代碼,看看我是否能夠適應它來做我所需要的。 – Eric

0

通常你可能需要一個ColorToBrushConverter,但不是一個BooleanToColor。

我會簡單地創建不同的風格與觸發每個酒吧,喜歡

 <Style.Triggers> 
      <DataTrigger Binding="{Binding IsOffline}" Value="True"> 
       <Setter Property="Background" Value="Salmon" /> 
      </DataTrigger> 
      <DataTrigger Binding="{Binding IsPrinting}" Value="True"> 
       <!--<Setter Property="Background" Value="Honeydew" />--> 
       <Setter Property="Background" Value="LightGreen" /> 
      </DataTrigger> 
     </Style.Triggers>