我正在写一个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