當您這樣做時,這意味着用戶控件的全部內容將被替換爲您提供的內容。
<custom:FullWidthExpander Width="200" HeaderBackground="Gray">
<Button />
</custom:FullWidthExpander>
要解決這個問題,你需要以不同的承載內容點點在你的用戶控件
加上一個依賴屬性的用戶控件
public object UserControlContent
{
get { return (object)GetValue(UserControlContentProperty); }
set { SetValue(UserControlContentProperty, value); }
}
public static readonly DependencyProperty UserControlContentProperty =
DependencyProperty.Register("UserControlContent", typeof(object), typeof(FullWidthExpander),
new PropertyMetadata(null));
那麼這個綁定到contentpresenter在usercontrol的xaml也爲你的用戶控件定義了一個名字,比如x:Name =「Root」。
<Expander Header="My expander header">
<Expander.Template>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="15"/>
</Grid.RowDefinitions>
<ContentPresenter x:Name="ContentPresenter" Grid.Row="0" Content="{Binding UserControlContent, ElementName=Root}" />
<ToggleButton Grid.Row="1" Content="Togglebutton">
</ToggleButton>
</Grid>
</ControlTemplate>
</Expander.Template>
</Expander>
最後你定義maindwindow XAML內容含量等
<custom:FullWidthExpander>
<custom:FullWidthExpander.UserControlContent>
<Button Content="Click me"/>
</custom:FullWidthExpander.UserControlContent>
</custom:FullWidthExpander>
你肯定會被覆蓋,而不僅僅是隱藏的按鈕? 您可以使用[Snoop](https://snoopwpf.codeplex.com/)查看您的控件在加載和運行時的樣子。 – KinSlayerUY
是的,當探聽我的應用程序時,除了ContentPresenter以外的所有東西都丟失了:/ – C4p741nZ
如果你把一個大小放到你的按鈕上,它還會發生嗎?按鈕將獲取所有可用的大小,以便自動生成擴展器大小可能是 – nkoniishvt