如何绑定到content控件的content属性?
我创建了自定义控件:
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));
}
在ViewModel中,我创建了一个此自定义控件类型的属性:
public CustomControl CustomControl { get; set; }
在视图中,我将此属性绑定到content控件:
<ContentControl x:Name="Custom" Content="{Binding CustomControl}"></ContentControl>
现在,我如何绑定到content控件的content属性?
发布于 2013-03-05 00:52:30
<ContentControl Content="{Binding ElementName=Custom, Path=Content}" />
不过,我不确定这会有什么影响。我怀疑它会抱怨UI元素已经有了父元素或类似的东西。
更新
如果我认为我正确地理解了你的问题,我不认为你可以使用绑定来做你想做的事情。这是另一种选择,它在内容更改时添加一个回调,以便您可以将新内容设置为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;
}
}
你可能需要一些错误处理。
https://stackoverflow.com/questions/15206621
复制相似问题