WPF 绑定到内容控件的内容属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15206621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:51:48  来源:igfitidea点击:

WPF bind to content control's content property

c#wpfbinding

提问by Shahin

How can I bind to content control's content property ?
I'v created custom control :

如何绑定到内容控件的内容属性?
我创建了自定义控件:

      public class CustomControl 
        {
         // Dependency Properties
public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(int), typeof(MainViewModel), new PropertyMetadata(0));
         }

In ViewModel I created a property of type of this custom control :

在 ViewModel 中,我创建了这个自定义控件类型的属性:

    public CustomControl CustomControl { get; set; }

In view I bind this property to content control :

鉴于我将此属性绑定到内容控件:

     <ContentControl x:Name="Custom" Content="{Binding CustomControl}"></ContentControl>

Now how can I bind to content control's content property?

现在如何绑定到内容控件的内容属性?

回答by JRoughan

<ContentControl Content="{Binding ElementName=Custom, Path=Content}" />

I'm not sure what effect this will have though. I have a suspicion it will complain about UI elements already having a parent or something similar.

我不确定这会产生什么影响。我怀疑它会抱怨 UI 元素已经有一个父元素或类似的东西。

Update

更新

If I think I understand your question correctly I don't think you can do what you want using bindings. This is an alternative which adds a callback for when the content is changed so you can set the new content to the property of your VM:

如果我认为我正确理解了您的问题,我认为您无法使用绑定来做您想做的事。这是一种替代方法,它在内容更改时添加回调,以便您可以将新内容设置为 VM 的属性:

class CustomControl : Control
{
    static CustomControl()
    {
        ContentControl.ContentProperty.OverrideMetadata(typeof(CustomControl), new PropertyMetadata(null, UpdateViewModel));
    }

    private static void UpdateViewModel(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as CustomControl;
        var viewModel = control.DataContext as MyViewModel;
        viewModel.CustomControl = control;
    }
}

You'll probably want some error handling in there.

您可能需要在那里进行一些错误处理。