繁体   English   中英

xaml 如何设置自定义控件的内容?

[英]How does xaml set content of a custom control?

为相当模糊的标题道歉 - 如果你能更好地表达,请更改。 我不确定 XAML 如何设置控件的内容,看起来幕后发生的事情与简单的Content = X有所不同,但我不确定是什么。

看,如果我有以下内容:

自定义控件:

using System;
using System.Windows.Controls;

namespace DemoWPF
{
    public class MyControl : UserControl
    {
        public MyControl()
        {
            base.Content = new Label() { Content = "Real Content" };
        }
        public new Object Content
        {
            get;
            set;
        }
    }
}

这做的很少,但覆盖了 Content 属性 - 本质上使其无用并使其仅包含一个显示“真实内容”的标签。

如果我想使用这个自定义控件,我可以通过两种方式来实现,不使用 xaml 和使用 xaml:

用例 1 - Window cs 文件(不含 xaml)

using System.Windows;
using System.Windows.Controls;

namespace DemoWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Content = new MyControl() { Content = new Label() { Content = "Should not show" } };
        }
    }
}

这按我的预期工作 - 窗口的内容(显然仅在运行时,因为没有使用设计器)显示为标签“真实内容”,而“不应该显示”标签没有出现。

用例 2 - 窗口(使用 xaml)

但是,如果不是上面的,而是通过 XAML 设置内容,那么设计和运行时都显示“不应显示”标签,而“真实内容”似乎被忽略:

<Window x:Class="DemoWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DemoWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <local:MyControl>
        <Label>Should not show</Label>
    </local:MyControl>

</Window>

这样做的原因是什么,xaml 与Use Case 1演示的有何不同?

发生这种情况是因为在ContentControl类声明中有一个ContentProperty属性声明:

System.Windows.Markup.ContentProperty("Content")
public class ContentControl ...

哪个集合使 XAML 表达式像

<local:MyControl>
    <Label>Should not show</Label>
</local:MyControl>

设置基类的 Content 属性,而不是你的新属性。

你必须写

<local:MyControl>
    <local:MyControl.Content>
        <Label>Should not show</Label>
    </local:MyControl.Content>
</local:MyControl>

请注意,您应该完全避免隐藏任何 WPF 控件属性。 它只会增加混乱而没有任何好处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM