自定义方法的返回类型与XAML中预期的不同
本文关键字:XAML 返回类型 自定义方法 | 更新日期: 2023-09-27 18:26:13
我有一个自定义方法,它返回一个将用作背景的Brush:
class ListBoxBackgroundSelector : BackgroundBrushSelector
{
public Brush fondo1 { get; set; }
public Brush fondo2 { get; set; }
private static bool usado = false;
public override Brush SelectBrushStyle(object item, DependencyObject container)
{
Brush fondo = null;
if (usado)
{
fondo = fondo1;
}
else
{
fondo = fondo2;
}
usado = !usado;
return fondo;
}
它从抽象类扩展而来
public abstract class BackgroundBrushSelector : ContentControl
{
public abstract Brush SelectBrushStyle(object item, DependencyObject container);
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
Background = SelectBrushStyle(newContent, this);
}
}
我在下面的XAML声明中使用它
<Grid.Background>
<local:ListBoxBackgroundSelector Background="{Binding}" fondo1="#19001F5B" fondo2="#FFFFFFFF" />
</Grid.Background>
但是Visual Studio突出显示了local:ListBoxBackgroundSelector行,并显示了一个错误:
无法指定特定值。预期值为"Brush"
但是该方法返回一个Brush!它的返回被指定给背景,这确实需要一个Brush。
该项目编译并运行,但当它到达包含所有这些内容的页面时,它只是以"未处理的异常"中断,没有其他内容可查看
中间有一些我没有意识到的东西。有人能帮忙吗?
您编写的方法返回一个笔刷,但您没有将该方法放置在Background
中,而是放置了从ContentControl
继承的类。在我看来,你现在有几个选择。对我来说,最明显的是将绑定到控制背景状态的任何东西,并添加一个转换器来返回正确的笔刷,类似于这样:
public class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return new SolidColorBrush((bool)value ? Colors.Red : Colors.Blue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
或者,您可以将已经作为主控件的类放置在视图中。
另一种选择是创建自己的MarkupExtension,类似于与转换器绑定,如果你想对它进行额外的控制