1

我想将用户控件属性设置为父控件中属性的值。例如,假设我的主窗口控件有一些初始配置数据。目前我在 XAML 中使用以下内容:

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

但这似乎需要两个依赖属性,一个在 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); }
    }    
  }
}

和 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); }
    }    
  }
}

我真的不需要观察任何变化,只是在创建时将数据传递到我的用户控件中。这是否可以对两者中的至少一个使用简单属性,或者我必须使用两个依赖属性来执行此(一次)初始化?

更新:Jay 的解决方案只在 MainWindow 类中留下了一个 CLR 属性:

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

现在,如果可以从 MyUserControl 类中删除依赖属性并将其替换为仍然通过 XAML 绑定(或其他一些 XAML 机制,因此我可以通过 XAML 传入数据源)初始化的简单属性。

4

1 回答 1

1

我可能弄错了,但是如果您可以绑定到其他类的 CLR 属性,我希望您可以绑定到您的MainWindow类的 CLR 属性。

你试过吗?

于 2010-12-29T16:37:49.983 回答