【问题标题】:Return type from custom method is not the same as expected in XAML自定义方法的返回类型与 XAML 中的预期不同
【发布时间】:2014-10-11 22:18:46
【问题描述】:

我有一个自定义方法,它返回将用作背景的 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!它的返回值被分配给背景,它确实需要一个画笔。

项目编译并运行,但当它到达包含所有这些东西的页面时,它只是以“未处理的异常”中断,没有其他可看的东西。

中间有一些我不知道的东西。有人可以帮忙吗?

【问题讨论】:

    标签: c# xaml windows-phone


    【解决方案1】:

    你写的方法返回一个画笔,但是你没有把方法放在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,类似于与转换器绑定,如果您想对其进行额外控制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多