gpt4 book ai didi

wpf - 您可以在 BorderBrush 属性的绑定(bind)中使用 IValueConverter 吗?

转载 作者:行者123 更新时间:2023-12-02 19:10:48 24 4
gpt4 key购买 nike

我有一个实现 IValueConverter 的类,该类旨在用于将 bool 值转换为 Brush。我尝试在与 Border 控件的 BorderBrush 属性的绑定(bind)中使用 IValueConverter:

<Window x:Class="DomPicker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cc="clr-namespace:CustomControls;assembly=CustomControls"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
DataContext="{Binding Path=Domains, RelativeSource={RelativeSource Self}}"
Height="350"
Title="My Title"
Width="525">

<cc:CarSystemWindow.Resources>
<cc:BooleanToBrushConverter x:Key="BrushConverter" True="Black" False="Transparent" />

<DataTemplate x:Name="DomainTemplate" DataType="DomainViewModel">
<Border BorderBrush="{Binding Converter=BrushConverter, Path=IsSelected}">
. . .
</Border>
</DataTemplate>
</cc:CarSystemWindow.Resources>

<Grid>
<ListBox . . . Name="DomainListBox" />
</Grid>
<Window>

下面是后面代码中的 Domains 属性的代码:

public static readonly DependencyProperty DomainsProperty =
DependencyProperty.Register( "Domains", typeof( ObservableCollection<DomainViewModel> ), typeof( MainWindow ), new PropertyMetadata( null ) );

public ObservableCollection<DomainViewModel> Domains {
get { return (ObservableCollection<DomainViewModel>) GetValue( DomainsProperty ); }
set { SetValue( DomainsProperty, value ); }
}

当我编译尚未完成的代码时,我在 BorderBrush 绑定(bind)上收到编译器错误:

The TypeConverter for "IValueConverter" does not support converting from a string.

这是IValueConverter的代码:

public class BooleanConverter<T> : IValueConverter {

public T False { get; set; }
public T True { get; set; }

public BooleanConverter( T trueValue, T falseValue ) {
// Set the values of True and false to the values we were passed.
True = trueValue;
False = falseValue;
}

public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
return value is bool && ( (bool) value ) ? True : False;
}

public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
return value is T && EqualityComparer<T>.Default.Equals( (T) value, True );
}
}

[ValueConversion( typeof( bool ), typeof( Brush ) )]
public class BooleanToBrushConverter : BooleanConverter<Brush> {

/// <summary>
/// Set us up so we convert true to a Black <see cref="SolidColorBrush"/> and
/// false to a Red SolidColorBrush.
/// </summary>
public BooleanToBrushConverter() :
base( new SolidColorBrush( Colors.Black ), new SolidColorBrush( Colors.Red ) ) { }
}

谁能告诉我我做错了什么?

最佳答案

您需要使用StaticResource来访问您的转换器

示例:

  <Border BorderBrush="{Binding IsSelected, Converter={StaticResource BrushConverter}}">

关于wpf - 您可以在 BorderBrush 属性的绑定(bind)中使用 IValueConverter 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345452/

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