2017-02-28 79 views
1

創建用戶控件我想用一個TextBlock的頭和另一個TextBlock的爲內容創建一個用戶控件2 TextBlock的WPF中

HeaderTextBlock.xaml

<UserControl x:Class="GetPageDataFacebookAPI.HeaderTextBlock" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:GetPageDataFacebookAPI" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Header" Opacity=".6" Margin="5" /> 
     <TextBlock Text="Text" Margin="5" /> 
    </StackPanel> 
</UserControl> 

但我怎麼能使用它,並結合值到標題和內容TextBlock?

<local:HeaderTextBlock Header="..." and Text="..." /> 

回答

1

你剛纔創建依賴屬性暴露在代碼中這些元素的後面。然後,當您在另一個視圖中使用控件時,您可以做到這一點。 向兩個TextBlock添加一個名稱,然後添加依賴屬性以在後面的代碼中更改它們。

<StackPanel Orientation="Horizontal"> 
    <TextBlock Text="Header" 
       Opacity=".6" 
       Margin="5" 
       Name="TextBlockHeader"/> 
    <TextBlock Text="Text" 
       Margin="5" 
       Name="TextBlockText"/> 
</StackPanel> 

代碼控制的背後...

public string Header 
    { 
     get { return (string)GetValue(HeaderProperty); } 
     set { SetValue(HeaderProperty, value); } 
    } 

    public static readonly DependencyProperty HeaderProperty = 
     DependencyProperty.Register(nameof(Header), typeof(string), typeof(HeaderTextBlock), new PropertyMetadata("", (s, e) => (s as HeaderTextBlock).TextBlockHeader.Text = (string)e.NewValue)); 

    public string Text 
    { 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 

    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register(nameof(Text), typeof(string), typeof(HeaderTextBlock), new PropertyMetadata("", (s, e) => (s as HeaderTextBlock).TextBlockText.Text = (string)e.NewValue)); 

然後你可以使用它在另一個視圖或控制是這樣的...工程與也具有約束力。

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 

    <local:HeaderTextBlock Header="{Binding Header}" Text="Hello WOrld"/> 

</Grid> 
0
  1. 創建兩個普通的CLR屬性,或

  2. 創建兩個DependencyProperty對應HeaderText如果你需要Binding

Tutorial