在XAML /代码隐藏中将项添加到集合中

时间:2014-11-10 13:33:46

标签: c# wpf xaml collections add

在XAML和代码隐藏中向项目集添加项目对我来说似乎有点奇怪。有人可以向我解释逻辑吗?

这是我继承自ListBox的测试控件类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Collections.Specialized;

namespace Test
{
    public class TestControl : ListBox
    {
        public TestControl() : base()
        {
            base.Items.Add("FOO");
        }
    }
}

以下是我在XAML中使用它的方法:

<UserControl x:Class="Test.ControlTest"
             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" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib" 
             mc:Ignorable="d" 
             d:DesignHeight="389" d:DesignWidth="512">
    <Grid>
        <local:TestControl>
            <local:TestControl.Items>
                <sys:String>BAR</sys:String>
            </local:TestControl.Items>
        </local:TestControl>
    </Grid>
</UserControl>

我在设计器中只看到“BAR”,但是当我运行应用程序时,同时显示“FOO”和“BAR”。这里的逻辑是什么?如果我订阅Loaded事件并在那里添加“FOO”,那么两个字符串在设计器中也是可见的。

在我实际更大的项目中,当使用类型为ObservableCollection的属性时,我遇到了同样的问题。即当我在构造函数中向集合中添加“default”项时,我在设计器中看不到它们。只有当我运行应用程序时。

另外,如果我在没有指定集合类名的情况下将项添加到我的集合中,那是否等同于Add方法调用?即:

<Grid>
    <local:MyClass>
        <local:MyClass.Items>
            <local:MyItem Text="First"/>
            <local:MyItem Text="Second"/>
            <local:MyItem Text="Third"/>
        </localMyClass.Items>
    </local:MyClass>
</Grid>

在上面的例子中,我在构造函数中添加了一个“default”项,当我运行我的应用程序而不是设计器时,这四个都是可见的。

与我创建新的MyItemCollection对象相比:

<Grid>
    <local:MyClass>
        <local:MyClass.Items>
            <local:MyItemCollection>
                <local:MyItem Text="First"/>
                <local:MyItem Text="Second"/>
                <local:MyItem Text="Third"/>
            </local:MyItemCollection>
        </localMyClass.Items>
    </local:MyClass>
</Grid>

在这种情况下,当我运行应用程序时,我的“默认”项目不可见,因为使用新的集合实例设置了Items属性。

0 个答案:

没有答案