0

我有什么:用户类

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>

我想 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>

它工作正常,但最终不是我想要的。如果 MyButton 的实例将为 Window 提供 DataContext 怎么办?

 public MainWindow()
        {
            //Set instance of MyButton as DataContext
            DataContext = new MyButton();
            InitializeComponent();
        }  

我想我必须在 XAML 端写

<ContentControl DataContext="{Binding}">
   <!--MyButton XAML code from DataTemplate here -->  

</ContentControl>


instead of

<local:MyButton></local:MyButton>

但它根本不起作用。我做错了什么?

4

2 回答 2

1

您应该尝试绑定到 ContentControl 的 Content 属性而不是 DataContext 属性:

<ContentControl Content={Binding } />

此外,ContentControl 的 DataContext 已经是 MyButton。

于 2013-07-26T07:58:06.090 回答
0

我不太确定你想在那里实现什么。如果您只是想扩展默认按钮的功能,您可以定义附加属性

为什么您希望 Window 的 DataContext 成为 Button?也许反过来?不确定我是否正确理解了那部分。

于 2013-07-26T12:59:32.650 回答