获取属性值 WPF

本文关键字:WPF 属性 获取 | 更新日期: 2023-09-27 18:33:19

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

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

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

获取属性值 WPF

由于您的 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>

在这里,您可以找到另一个完美的答案。

问候。