我正在寫一個WPF控件,意思是以同樣的方式將一個容器Border
和ScrollViewer
作爲容器。它被稱爲EllipsisButtonControl
,它應該在其內容的右側放置一個省略號按鈕。下面是我打算如何爲它使用的例子:在充當容器的WPF控件中,如何放置內容?
<local:EllipsisButtonControl>
<TextBlock Text="Testing" />
</local:EllipsisButtonControl>
這裏是EllipsisButtonControl
的XAML:
<ContentControl
x:Class="WpfApplication1.EllipsisButtonControl"
x:Name="ContentControl"
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"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0" Content="{Binding ElementName=ContentControl, Path=Content}" />
<Button Grid.Column="1" Command="{Binding ElementName=ContentControl, Path=Command}" Margin="3,0" Width="30" Height="24" MaxHeight="24" VerticalAlignment="Stretch" Content="..." />
</Grid>
</ContentControl>
這裏是後面的代碼:
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class EllipsisButtonControl
{
public EllipsisButtonControl()
{
InitializeComponent();
}
public static string GetCommand(DependencyObject obj)
{
return (string)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, string value)
{
obj.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
name: "Command",
propertyType: typeof(ICommand),
ownerType: typeof(EllipsisButtonControl),
defaultMetadata: new UIPropertyMetadata());
}
}
這並未沒有工作。它以System.Runtime.Remoting.RemotingException
使設計者崩潰。
我相信X30L的ContentPresenter
的ContentPresenter
上的綁定是錯誤的,但我不知道如何使它正確。使該行參考控件內容的適當語法是什麼? (例如,在使用示例中定義的TextBlock
)
編輯:
捅提供以下(包括工作代碼)一個全面的答案,但對於其他的誰可能分享我最初誤解的好處,讓我總結這裏的關鍵概念是:容器控制本身不能「放置內容」。它通過定義一個模板來達到預期的效果,該模板修改了調用XAML呈現內容的方式。解決方案的其餘部分來自該前提。
爲什麼命令是附屬屬性,而不是常規的依賴屬性? – Clemens
嗯......因爲我正在複製的例子就是這樣......提示你的問題,我研究了附加屬性,並瞭解到我應該在第23行使用DependencyProperty.Register(),而不是DependencyProperty.RegisterAttached() 。 謝謝。 – Lork
*「容器控件本身不能」放置內容「。」* - 它可以,但只有一個內容,因此設置外部內容會替換內部內容。你想要的是內容放置在內的「框架」(=模板)。 – poke