c# - 如何使用 UIElement 依赖属性实现 WPF 用户控件?

标签 c# wpf mvvm dependency-properties uielement

我有一个用户控件,后面有这段代码:

/// <summary>
/// The text to use for the header.
/// </summary>
public UIElement HeaderText
{
    get { return (UIElement) GetValue(HeaderTextProperty); }
    set { SetValue(HeaderTextProperty, value); }
}

public static DependencyProperty HeaderTextProperty =
    DependencyProperty.Register("HeaderText",
                                typeof(UIElement),
                                typeof(Panel),
                                new PropertyMetadata(null, new PropertyChangedCallback(HeaderTextPropertyChanged)));

private static void HeaderTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var control = d as Panel;
    if (control != null)
    {
        control.HeaderText = (UIElement) e.NewValue;
    }
}

而这个 XAML:
<TextBlock Text="{TemplateBinding local:CustomPanel.HeaderText}" />

我正在尝试像这样使用用户控件:
<controls:CustomPanel>
    <controls:CustomPanel.HeaderText>
        <TextBlock Text="Foo " />
        <TextBlock Text="{Binding Bar}" />
        <TextBlock Text=" baz." />
    </controls:CustomPanel.HeaderText>
</controls:CustomPanel>

但是,我得到的是空白/空文本。

如果我更改 UIElement,我可以让它工作进入 string在代码隐藏中,但 我想同时接受 string , TextBlock 几乎所有UIElement这对文本有意义。

我怎样才能做到这一点?

最佳答案

不要使用 TextBlock在您的控制中,但一个 ContentPresenter (并绑定(bind) Content ),它可以托管任何东西。使属性类型object并将名称更改为 Header为了一致性。

(作为旁注:通常您具有与 Header 一起使用的附加属性,即 HeaderTemplateHeaderTemplateSelector 。如果 ContentPresenter 在模板中,则可以将其绑定(bind)到所有三个属性通过将 ContentSource 设置为 "Header" )

关于c# - 如何使用 UIElement 依赖属性实现 WPF 用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866570/

相关文章:

c# - 将委托(delegate)作为参数的方法?

WPF MVVM 数据模板绑定(bind)

c# - 每当数据库中的数据更新时通知客户

c# - TIBCO EMS 服务器是否管理重新连接?或者客户呢?

c# - 数据库更新的词典/列表速度

wpf - 将 ComboBox 数据绑定(bind)到 DataGrid 中的 SelectedItem

mvvm - 声明 ReactiveCommand 后如何更新 CanExecute 值

c# - ThreadPool.QueueUserWorkItem 具有任意数量的线程

c# - 在运行时动态修改样式(添加触发器)

wpf - 如何防止 WPF 对话框中的键盘事件渗透到调用它的 MFC 应用程序?