[英]Why doesn't my button appear in the ContentPresenter area?
<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>
按鈕應出現在藍色和黃色矩形之間。
我究竟做錯了什么?
問題是您要定義ContentControl的內容兩次:一次在ContentControl中,一次在Window.xaml
。 Window.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>
我不是專業人士,但我會改變這些方面:
<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"/>
簡:您忘了為第一行定義行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.