简体   繁体   English

UserControl中的DependencyProperty

[英]DependencyProperty in a UserControl

I'm creating a UserControl "UC". 我正在创建一个UserControl“ UC”。 I have my class with data "AClass". 我的课上有数据“ AClass”。 I want an object of this class to be a DP in my UserControl. 我希望此类的对象成为UserControl中的DP。 So i put the definition in UC: 所以我把定义放在UC中:

public static readonly DependencyProperty AProperty =
    DependencyProperty.Register("A", typeof(AClass),
    typeof(UC), new FrameworkPropertyMetadata(new AClass()));

public AClass A
{
    get { return (AClass)GetValue(AProperty); }
    set { SetValue(AProperty, value); }
}    

Here's how I create my control in XAML: 这是我在XAML中创建控件的方式:

xmlns:l="clr-namespace:MyWorkspace"
// ...
<Grid>
    <l:UC Height="100" Width="150" Activity="{Binding a}" />
</Grid>

I defined "a" in the code-behind file: 我在代码隐藏文件中定义了“ a”:

public partial class MainWindow : Window
{
    public AClass a {get; set;}
    public MainWindow()
    {
        DataContext = this;
        a = // create an object
        InitializeComponent();
    }
}

Next, in my UC I want to refer to "A" and use one of its property: 接下来,在我的UC中,我想引用“ A”并使用其属性之一:

private void DoSomethingInUC()
{
   int size = A.AsProperty;
   // ...
}

The problem is that every time I refer to "A" it is uninitialized (ie "AsProperty" contains default value). 问题是,每次我引用“ A”时,它都是未初始化的(即“ AsProperty”包含默认值)。

What's wrong in that ? 那有什么问题?

1) How can your A DP be of type double and AClass? 1)您的A DP如何成为double AClass类型?

2) You most likely want to avoid doing this : 2)您最有可能希望避免这样做:

new FrameworkPropertyMetadata(new AClass())

because the exact AClass instance you new up right there will be shared as default by all of your UserControl instances. 因为您在新创建的确切AClass实例将被所有UserControl实例默认共享。

3) You have to make your MainWindow implement INotifyPropertyChanged (prefer making a MainWindowViewModel) and have your a property RaisePropertyChanged inside it's setter. 3)您必须使您的MainWindow实现INotifyPropertyChanged(更喜欢制作MainWindowViewModel),并在其设置器中设置属性RaisePropertyChanged。

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

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