简体   繁体   中英

WPF Button Image Source Binding String Dependency Property

This worked in UWP but I can't get the image to show using WPF XAML.

I start by defining a UserControl which binds the path of the image file:

<Grid Height="70" Width="70">
    <Border Style="{StaticResource border}">
        <Button Style="{StaticResource button}">
            <Image Source="{Binding prop_image}"/>
        </Button>
    </Border>
</Grid>

I define the dependency property as:

public static readonly DependencyProperty prop_image =
DependencyProperty.Register("prop_image_path", typeof(string),
typeof(user_control), null);

public string prop_image_path
{
    get { return (string)GetValue(prop_image); }
    set { SetValue(prop_image, value); }
}

I then try to consume it as:

<local:user_control Grid.Column="1" Grid.Row="2"
    prop_image_path="/Assets/my.png"/>

which is the exact same as UWP but with Binding instead of x:bind. when I create a button and set the image it works . . . but it doesn't display the alpha channel(which I guess means I have to use an alpha mask and have two files.) aside from this, moving a bunch of stuff from UWP to WPF XAML was a snap.

At first, you are using the wrong property path in {Binding prop_image} , which should be {Binding prop_image_path} . Since this Binding is in a UserControl's XAML to one of its own properties, you should also specify the source object of the Binding to be the UserControl instance, like:

<Image Source="{Binding prop_image_path,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>

Besides that, the WPF dependency property system requires that you adhere to naming conventions for the dependency property identifier field.

It must be named like the property with a Property suffix:

public static readonly DependencyProperty prop_image_pathProperty =
    DependencyProperty.Register(
        "prop_image_path",
         typeof(string),
         typeof(user_control),
         null);

You may also notice that your naming scheme is a little uncommon. According to widely accepted conventions, C#/.NET type and property names should use Pascal Casing, ie

public class MyUserControl
{
    public static readonly DependencyProperty ImagePathProperty =
        DependencyProperty.Register(
            nameof(ImagePath),
            typeof(string),
            typeof(MyUserControl));

    public string ImagePath
    {
        get { return (string)GetValue(ImagePathProperty); }
        set { SetValue(ImagePathProperty, value); }
    }
}

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