【问题标题】:WPF - Passing parameter from Dialog Window to UserControlWPF - 将参数从对话框窗口传递给用户控件
【发布时间】:2017-05-08 12:27:30
【问题描述】:

我正在使用 DependencyProperty 将参数从 DialogWindow 传递到 UserControl。 我希望在 UserControl 构造函数中使用该参数,以便将其传递给视图模型。

该属性始终返回 null,并且永远不会被设置。

代码:

主窗口:

var dialog = new DialogWindow();
dialog.ShowDialog();

DialogWindow.xaml

<TabControl>
    <TabItem Header="Data Source">
        <local:DataSourceView Test="Something" />
    </TabItem>
</TabControl>

DataSourceView.xaml.cs

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register("Test", typeof(object), typeof(DataSourceView));
public object Test {
    get { return (object)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}
public DataSourceView() {
    InitializeComponent();
    DataContext = new DataSourceViewModel(Test);// Test is always null
}

【问题讨论】:

    标签: c# wpf xaml mvvm dependency-properties


    【解决方案1】:

    您可以将DependencyProperty.Register 方法的重载与PropertyMetadata 一起使用,该方法将具有PropertyChangedCallback 参数并观察数据绑定过程。

        public static readonly DependencyProperty TestProperty =
          DependencyProperty.Register("Test", typeof(object), typeof(DataSourceView), new PropertyMetadata(TestPropertyChangedCallback
        ));
    
        private static void TestPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.NewValue);
            System.Diagnostics.Debug.WriteLine(e.OldValue);
        }
    

    以下链接包含类似问题的解决方案:

    Passing Parameters between xaml window and usercontrol WPF

    【讨论】:

    • 这里也有类似的情况:link你应该把DataContext的设置移到Loaded事件处理程序中。
    • 使用回调方法,我发现在 View 实例完成后会设置属性,并使用您在评论中提供的链接,我现在可以访问正确的值。您能否更新您的答案以在您的评论中包含链接。谢谢:)
    【解决方案2】:

    "该属性始终返回 null,并且永远不会被设置。" - 是错的。该属性在 DataSourceView 构造函数中为 null。创建 DataSourceView 实例后,属性将设置为“Something”。

    【讨论】:

    • 是的,你是对的,我注意到使用 madiden 的回答中建议的回调方法。谢谢你的回答:)
    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 2014-03-10
    • 2013-10-18
    • 2012-05-06
    • 1970-01-01
    • 2010-12-15
    • 2014-03-10
    • 1970-01-01
    相关资源
    最近更新 更多