用户控件的依赖属性未绑定 [英] User control's dependency property not binding

查看:42
本文介绍了用户控件的依赖属性未绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有依赖属性的用户控制.当我尝试在 Windows 中绑定它时,它不起作用.但是,当我将绑定更改为普通参数(在这种情况下为 true)时,它正在工作.我需要做什么才能使我的绑定工作?也许与DataContext有关?这是我的代码:

I have user control with dependency property. When I try bind it in windows it doesn't work. But when I change binding to normal parameter (in this situation, true) it's working. What i need to do to make my binding working? Maybe something with DataContext? Here is my code:

第一个用户控件的 xaml:

First user control's xaml:

<UserControl x:Class="DPTest.CustomUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="100" d:DesignWidth="200"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <TextBlock Text="{Binding Property}"/>
</Grid>
</UserControl>

背后的代码:

public partial class CustomUserControl : UserControl, INotifyPropertyChanged
{
    public static readonly DependencyProperty DPTestProperty = DependencyProperty.Register("DPTest", typeof(bool), typeof(CustomUserControl), new PropertyMetadata(default(bool), propertyChangedCallback));
    public bool DPTest
    {
        get
        {
            return (bool)GetValue(DPTestProperty);
        }
        set
        {
            SetValue(DPTestProperty, value);
        }
    }
    private bool _property;
    public bool Property
    {
        get
        {
            return _property;
        }
        set
        {
            _property = value;
            RaisePropertyChanged("Property");
        }
    }
    private static void propertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as CustomUserControl;
        control.Property = (bool)e.NewValue;
    }

    public CustomUserControl()
    {
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

在我放置这个用户控件数据上下文的窗口中设置为我的视图模型:

In the windows where i put this user control data context is set to my view model:

<phone:PhoneApplicationPage
x:Class="DPTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:my="clr-namespace:DPTest"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
DataContext="{Binding Main, Source={StaticResource Locator}}">

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
        <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <my:CustomUserControl Name="cstom" DPTest="{Binding Property}"/>
    </Grid>

</Grid>

</phone:PhoneApplicationPage>

在视图模型中,我有绑定到 DPTest 的属性.

In the view model I have property which is binded to DPTest.

public class MainViewModel : ViewModelBase
{
    private bool _property;

    public bool Property
    {
        get { return _property; }
        set
        {
            _property = value;
            RaisePropertyChanged("Property");
        }
    }

    public MainViewModel()
    {
        Property = true;
    }
}

当我运行这个应用程序时,Textblock 的值为 False 但这应该是 True 并且甚至没有调用 propertyChangedCallback.我需要做什么?

When I run this application Textblock have value False but this should be True and propertyChangedCallback isn't even called. What i need to do?

谢谢

推荐答案

您已经将 UserControl DataContext 绑定到自身,因为您想将 CustomUserControl 中的 Property 绑定到里面的 TextBlock它完全没问题.

You have bind UserControl DataContext to itself since you want to bind Property present in CustomUserControl to TextBlock inside it which is completely fine.

但是当您在 Window 中使用 CustomUserControl 时,它不会继承 Window 的 DataContext,因为它在 UserControl 声明中显式设置.因此,绑定引擎正在尝试在 UserControl 中查找它无法正常工作的属性.

But when you use CustomUserControl in Window, it won't inherit Window's DataContext since its explicitly set on UserControl declaration. So, binding engine is trying to look for property in UserControl which it can't fine.

注意:绑定引擎在它的 DataContext 中查找属性,否则会被指示使用 RelativeSource、ElementName、x:Reference 等查找其他地方.

所以你需要手动为绑定引擎提供这样的属性实例:

So you need to manually provide binding engine the property instance like this:

<my:CustomUserControl Name="cstom"
                      DPTest="{Binding Path=DataContext.Property, 
                                       ElementName=LayoutRoot}"/>

<小时>

使用 DPTest="True" 的说明:


Explanation for working with DPTest="True":

由于您已经手动将值提供给 DP,因此绑定引擎不必担心在 DataContext 中查找它.

Since you already manually provided the value to DP, binding engine doesn't have to worry about finding it in DataContext.

这篇关于用户控件的依赖属性未绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆