Tôi có một lớp thực hiện IValueConverter
được thiết kế để được sử dụng để chuyển đổi giá trị Boolean thành Brush
. Tôi đang cố gắng sử dụng IValueConverter
trong một ràng buộc với BorderBrush
tài sản của một Border
điều khiển:Bạn có thể sử dụng một IValueConverter trong một ràng buộc trên tài sản BorderBrush?
<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>
Đây là mã cho các tài sản Domains trong các mã sau:
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); }
}
Khi tôi biên dịch mã, mà không có nghĩa là hoàn thành, tôi nhận được một lỗi trình biên dịch trên ràng buộc BorderBrush
:
The TypeConverter for "IValueConverter" does not support converting from a string.
Đây là mã cho 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)) { }
}
Bất cứ ai có thể cho tôi biết tôi đang làm gì sai?
tôi biết rằng !!! Cảm ơn! –
Ồ wow. Bây giờ tôi cảm thấy ngu ngốc. Cảm ơn @ sa_ddam213, bạn đã thực hiện một ngày của tôi! :-) – BrainSlugs83
Tôi cảm thấy chính xác như trên hai bình luận và điều đó quá cùng một lúc. –