簡體   English   中英

用戶類為DataContext時使用DataTemplate和ContentControl

[英]DataTemplate and ContentControl when user class as DataContext

我所擁有的:用戶類

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實例將DataContext for Window怎么辦?

 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>

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

您應該嘗試綁定到ContentControl的Content屬性而不是DataContext屬性:

<ContentControl Content={Binding } />

此外,ContentControl的DataContext已經是MyButton。

我不太確定您要在此達成什么目標。 如果您只是想擴展默認按鈕的功能,則可以定義附加屬性

為什么要讓Window的DataContext成為Button? 也許反過來? 不確定我是否正確理解了該部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM