[英]DataTemplate and ContentControl when user class as DataContext
What I have: User class 我所拥有的:用户类
public class MyButton
{
public String ButtonProperty { get; set; }
public String LabelProperty { get; set; }
public MyButton()
{
ButtonProperty = "MyButtonText!";
LabelProperty = "LabelText!";
}
}
DataTemplate defined in window resources 窗口资源中定义的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>
I want to DataTemplate will draw instead of instance of MyButton class 我想以DataTemplate代替MyButton类的实例绘制
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication7"
Title="MainWindow" Height="500" Width="800">
<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>
<!-- Create instance of MyButton in XAML-->
<local:MyButton></local:MyButton>
</Window>
It works fine, but it is not what I want at the end. 它工作正常,但最终不是我想要的。 What if instance of MyButton will DataContext for Window?
如果MyButton实例将DataContext for Window怎么办?
public MainWindow()
{
//Set instance of MyButton as DataContext
DataContext = new MyButton();
InitializeComponent();
}
I thought I must write that in XAML-side 我以为我必须在XAML端写
<ContentControl DataContext="{Binding}">
<!--MyButton XAML code from DataTemplate here -->
</ContentControl>
instead of
<local:MyButton></local:MyButton>
but it doesn't work at all. 但它根本不起作用。 what I am doing wrong?
我做错了什么?
You should try to bind to the Content property of your ContentControl instead of the DataContext property : 您应该尝试绑定到ContentControl的Content属性而不是DataContext属性:
<ContentControl Content={Binding } />
Besides, the DataContext of the ContentControl is already the MyButton. 此外,ContentControl的DataContext已经是MyButton。
I'm not really sure what are you trying to achieve there. 我不太确定您要在此达成什么目标。 IF you simply want to extend the functionality of the default Button you could define attached properties
如果您只是想扩展默认按钮的功能,则可以定义附加属性
Why would you want the DataContext of your Window to be the Button? 为什么要让Window的DataContext成为Button? Maybe the other way around?
也许反过来? Not sure I understood that part correctly.
不确定我是否正确理解了该部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.