获取属性值WPF

时间:2016-02-04 03:22:45

标签: c# wpf xaml

我正在尝试从属性中获取值但不起作用我总是得到一个空值。

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"/>

我总是获得下一个输出: 路径:

1 个答案:

答案 0 :(得分:0)

因为你的ImageSource必须绑定到它的父DependencyProperty(后面的代码定义),你必须将你的绑定定义为你的UserControl(我们将它命名为 This ) 。因此,请尝试以下一种方式更改您的xaml:

Xaml代码

<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.

问候。