gpt4 book ai didi

c# - 将颜色传递给IValueConverter

转载 作者:行者123 更新时间:2023-12-03 10:21:26 25 4
gpt4 key购买 nike

我正在使用MVVM设计模式制作WPF应用程序。该应用程序的一部分是信号强度栏。我们仅用一个矩形用户控件创建了它,并创建了一个4列网格,因此我们要做的就是更改控件的背景色或前景色。

我的想法是简单地为4个部分中的每个部分存储 bool 值并使用值转换器。但是,此控件有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}
更新
这是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;
}
}
}
主题\Generic.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>

关于c# - 将颜色传递给IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com