C# 当用户类作为DataContext时,DataTemplate和ContentControl
我所拥有的: 用户类C# 当用户类作为DataContext时,DataTemplate和ContentControl,c#,wpf,C#,Wpf,我所拥有的: 用户类 public class MyButton { public String ButtonProperty { get; set; } public String LabelProperty { get; set; } public MyButton() { ButtonProperty = "MyButtonText!"; LabelProperty =
public class MyButton
{
public String ButtonProperty { get; set; }
public String LabelProperty { get; set; }
public MyButton()
{
ButtonProperty = "MyButtonText!";
LabelProperty = "LabelText!";
}
}
在窗口资源中定义的DataTemplate
<Window.Resources>
<DataTemplate DataType="{x:Type local:MyButton}">
<Border Width="100" Height="100" BorderThickness="2" BorderBrush="Aquamarine">
<StackPanel >
<Button>
<TextBlock Text="{Binding ButtonProperty}"></TextBlock>
</Button>
<Label Content="{Binding LabelProperty}"></Label>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
我想我必须把它写在XAML的侧面
<ContentControl DataContext="{Binding}">
<!--MyButton XAML code from DataTemplate here -->
</ContentControl>
instead of
<local:MyButton></local:MyButton>
而不是
但它根本不起作用。我做错了什么?您应该尝试绑定到ContentControl的Content属性,而不是DataContext属性:
<ContentControl Content={Binding } />
此外,ContentControl的DataContext已经是MyButton了。我真的不确定您想在这里实现什么。如果只是想扩展默认按钮的功能,可以定义
为什么希望窗口的DataContext成为按钮?也许相反?不确定我是否正确理解了该部分。使用Content属性,它可以工作,谢谢。但是,尽管DataContext已经是我的按钮(我想它是从Window.DataContext获取的?),但我需要明确地设置内容。i、 是的,我是认真的。这是否如你所愿,或者你是否需要一些不同的东西。我将用一些代码更新我的答案以澄清。关于DataContext,只要不明确定义子对象的DataContext,它就会沿着可视树传递。
<ContentControl DataContext="{Binding}">
<!--MyButton XAML code from DataTemplate here -->
</ContentControl>
instead of
<local:MyButton></local:MyButton>
<ContentControl Content={Binding } />