简体   繁体   中英

Get property value WPF

I am trying get a value from a property but isn't working I always get a null value.

string imageNormal;

    public static readonly DependencyProperty ImageNormalProperty =
        DependencyProperty.Register("ImageNormal", typeof(string), typeof(MainWindow));

public string ImageNormal
    {
        get { return (string)GetValue(ImageNormalProperty); }
        set { SetValue(ImageNormalProperty, value); }
    }

public ButtonImageStyle()
    {
        InitializeComponent();
        DataContext = this;
        Console.WriteLine("Path: " + ImageNormal);
    }

Xaml ButtonImageStyle.xaml:

<Image Source="{Binding ImageNormal}" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />

Xaml MainWindow.xaml:

<local:ButtonImageStyle HorizontalAlignment="Left" Height="60" VerticalAlignment="Top" Width="88" ImageNormal="C:/Users/Xafi/Desktop/add.png"/>

I always obtain next output: Path:

since your ImageSource is have to be binded to it's parent DependencyProperty (which is defined to your code behind), you have to define your binding to be rlative to your UserControl (let's name it This ). Thus please try to change your xaml in the next way:

Xaml code

<UserControl x:Class="SomeBindingExampleSOHelpAttempt.ButtonImageStyle"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" x:Name="This">
<Grid>
    <Image Source="{Binding ElementName=This, Path=ImageNormal, UpdateSourceTrigger=PropertyChanged}" 
           Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid></UserControl>

Here you can find an additional perfect answer.

Regards.

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