开发者

Tying user control property to named parent property

I want to set a user control property to the value of a property in a parent control. For example, let's say my main window control has some initial configuration data. Currently I use the following in XAML:

<Window x:Class="MyProject.MainWindow"
        x:Name="TopWindow" ... >
  ...
  <local:MyUserControl Config="{Binding ElementName=TopWindow,
                                Path=MyUserControlConfig, Mode=OneTime}" />
</Window>

But this appears to require two dependency properties, one in the MainWindow (MyUserControlConfig):

namespace MyProject
{
  public partial class MainWindow: Window
  {
    public static readonly DependencyProperty MyUserControlConfigProperty=
      DependencyProperty.Register("MyUserControlConfig", 
        typeof(UserControlConfig), typeof(MainWindow));

    public UserControlConfig MyUserControlConfig
    {
      get { return (UserControlConfig) 
        GetValue(MyUserControlConfigProperty); }
      set { SetValue(MyUserControlConfigProperty, value); }
    }    
  }
}

and one in MyUserControl (Config):

namespace MyProject
{
  public partial class MyUserControl: UserControl
  {
    public static readonly DependencyProperty ConfigProperty=
      DependencyProperty.Register("Config", 
      typeof(UserControlConfig), typeof(MainWindow));

    public UserControlConfig Config
    {
      get { return (UserControlConfig) GetValue(ConfigProperty); }
      set { SetValue(ConfigProperty, value); }
    }    
  }
}

I really don't need to observe any changes, just to pass data into my user control at the time of creation. Is this possible to do using simple properties for at least one of the two or must I us开发者_如何学运维e two dependency properties to perform this (one time) initialization?

Update: Jay's solution leaves us with just a CLR property in the MainWindow class:

namespace MyProject
{
  public partial class MainWindow: Window
  {
    public UserControlConfig MyUserControlConfig {get; private set;}
    ...
  }
}

Now if it was just possible to remove the dependency property from the MyUserControl class and replace it with a simple property that still gets initialized via XAML binding (or some other XAML mechanism, so I can pass in the data source via XAML).


I could be mistaken, but if you can bind to CLR properties on other classes, I'd expect you could bind to a CLR proprety on your MainWindow class.

Have you tried that?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜