WPF嵌套用户控件依赖项绑定属性

r8xiu3jd  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(114)

我有一个WPF应用程序使用Prism使用ViewModels,我遇到了一个嵌套的UserControl的问题,它有自己的CodeBehind和DependencyBinding属性。
使用此代码,PanZoomControl中的绑定不起作用,图像未设置,并且在调试中未调用getset
ImagePreviewView.xaml

<UserControl x:Class="Modules.ImagePreviewView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:prism="http://prismlibrary.com/"
         xmlns:controls="clr-namespace:UI.Infrastructure.Controls;assembly=UI.Infrastructure"
         prism:ViewModelLocator.AutoWireViewModel="True">
<x:Code>
    <![CDATA[ public ImagePreviewView() { InitializeComponent(); } ]]>
</x:Code>

<Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <controls:PanZoomControl Grid.RowSpan="3"
                             Grid.ColumnSpan="3" 
                             ImageSrc="{Binding ImagePreviewVM.ImagePreview}">
    </controls:PanZoomControl>

</Grid>

PanZoomControl.xaml

<UserControl x:Class="UI.Infrastructure.Controls.PanZoomControl"
             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="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding ImageSrc}" />
    </Grid>
</UserControl>

PanZoomControl.xaml.cs

public partial class PanZoomControl : UserControl
{
    #region Dependency Properties
    public static readonly DependencyProperty ImageSourceProperty =
       DependencyProperty.Register("ImageSrc", typeof(object), typeof(PanZoomControl));

    public object ImageSrc
    {
        get { return GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }
    
    #endregion

    public PanZoomControl()
    {
        InitializeComponent();
    }
}
ijxebb2r

ijxebb2r1#

ImageSrc不是DataContext的属性,而是控件本身的属性,所以更改绑定源:

<UserControl x:Class="UI.Infrastructure.Controls.PanZoomControl"
             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" 
             Name="uc"
             mc:Ignorable="d"  
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding ImageSrc, ElementName=uc}" />
    </Grid>
</UserControl>

此外,由于DP是以名称ImageSrc注册的,因此应将其命名为ImageSrcProperty

相关问题