简体   繁体   中英

Return type from custom method is not the same as expected in XAML

I have a custom method that returns a Brush that will be used as a background:

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;
    }

which extends from the abstract class

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);
    }
}

And I am using it in the following XAML declaration

<Grid.Background>
   <local:ListBoxBackgroundSelector Background="{Binding}" fondo1="#19001F5B" fondo2="#FFFFFFFF" />
</Grid.Background>

But Visual Studio highlights the local:ListBoxBackgroundSelector line with an error that says

The specific value cannot be assigned. The expected value is "Brush"

But the method returns a Brush! And its return is being assigned to the Background, which indeed expects a Brush.

The project compiles and run, but when it reaches the page where is all this stuff, it just breaks with an "Unhandled Exception" and nothing else to look at.

There is something in the middle that I am not aware of. Can anyone help?

The method you wrote returns a brush, but you didn't place the method in the Background , you placed your class, which inherits from ContentControl . The way I see it, you now have a few options. The most obvious to me would be to place a binding to whatever controls the state of your background, and add a converter to return the correct brush, something like this:

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();
    }
}

Or you can place the class you already have as the main control in your view.

Another option is to create a MarkupExtension of your own, similar to binding with converter, if you'd like that bit of extra control over it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM