2012-04-22 30 views
0
<ContentControl x:Class="Test.MyControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      Width="200" Height="200" > 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="*" /> 
      <RowDefinition Height="*" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 
     <Rectangle Fill="Blue"/> 
     <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" /> 
     <Rectangle Fill="Yellow" Grid.Row="2"/> 
    </Grid> 
</ContentControl> 

<Window x:Class="Test.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:Test="clr-namespace:Test" Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Test:MyControl2> 
      <Button/> 
     </Test:MyControl2> 
    </Grid> 
</Window> 

該按鈕應該出現在藍色和黃色矩形之間。爲什麼我的按鈕不出現在ContentPresenter區域中?

我在做什麼錯?

+0

我不認爲你可以把一個按鈕的用戶控件內部這樣,你爲什麼不把按鈕控件內? – Habib 2012-04-22 15:49:00

回答

3

問題是,您正在定義ContentControl的內容兩次:一次在您的ContentControl中,一次在Window.xamlWindow.xaml中的內容會覆蓋您的ContentControl中的內容,因此您會看到一個沒有上方和下方的彩色矩形的按鈕。

如果您想要更改ContentControl中內容的呈現方式,您需要將相關標記放在ContentControl的ContentTemplate中。你上面介紹的ContentControl中需要看起來像如下:

<ContentControl x:Class="Test.MyControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Width="200" Height="200" > 
    <ContentControl.ContentTemplate> 
     <DataTemplate> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="*" /> 
        <RowDefinition Height="*" /> 
        <RowDefinition Height="*" /> 
       </Grid.RowDefinitions> 
       <Rectangle Fill="Blue"/> 
       <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" /> 
       <Rectangle Fill="Yellow" Grid.Row="2"/> 
      </Grid> 
     </DataTemplate> 
    </ContentControl.ContentTemplate> 
</ContentControl> 
-1

我不親,但我會改變這些行:

<Rectangle Fill="Blue"/> 
    <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" /> 
    <Rectangle Fill="Yellow" Grid.Row="2"/> 

要這樣:

<Rectangle Fill="Blue" Grid.Row="0"/> 
    <ContentPresenter Grid.Row="1" Content="{TemplateBinding ContentControl.Content}" /> 
    <Rectangle Fill="Yellow" Grid.Row="2"/> 

短:你忘了定義行中的第一個。

+0

默認行和列是0(第一個) – 2012-04-22 15:42:59

相關問題