简体   繁体   English

获取属性值WPF

[英]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: Xaml ButtonImageStyle.xaml:

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

Xaml MainWindow.xaml: 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 ). 由于必须将ImageSource绑定到其父DependencyProperty(在后面的代码中定义),因此必须将绑定定义为与UserControl相关(将其命名为This )。 Thus please try to change your xaml in the next way: 因此,请尝试通过以下方式更改您的xaml:

Xaml code 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. 在这里您可以找到其他的完美答案。

Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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