【问题标题】:base class property always null when creating objects from xaml从 xaml 创建对象时,基类属性始终为空
【发布时间】:2011-03-08 21:34:04
【问题描述】:

我正在尝试从 xaml 实例化一个对象。对象的类继承自基类。除了未从 xaml 正确设置基类属性(“键”)外,一切正常。它始终为空。对象的属性本身从 xaml 设置为 OK。另外,当我从代码中设置 Key 属性时,它设置得很好。

我在 MainWindow 方法的右括号上放了一个断点来查看对象数据。悬停细节告诉我 Key 属性始终为空。

任何想法我做错了什么?

<?xml version="1.0" encoding="utf-8" ?>
<GroupUiItem xmlns="clr-namespace:Configurator.UiCore"
         Key="key_grp1" UserName="grp1">
    <ParameterUiItem Key="key_par1" UserName="par1"/>
    <GroupUiItem Key="key_grp2" UserName="grp2">
        <ParameterUiItem Key="key_par2" UserName="par2"/>
        <ParameterUiItem Key="key_par3" UserName="par3"/>
    </GroupUiItem>
    <ParameterUiItem Key="key_par4" UserName="par4"/>
    <ParameterUiItem Key="key_par5" UserName="par5"/>
    <ParameterUiItem Key="key_par6" UserName="par6"/>
</GroupUiItem>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        GroupUiItem ConfigUi = new GroupUiItem();

        InitializeComponent();

        using (FileStream stream = new FileStream("XMLFile1.xaml", FileMode.Open, FileAccess.Read))
        {
            ConfigUi = XamlReader.Load(stream) as GroupUiItem;
        }
        ConfigUi.Key = "key_grp1"; // this works OK

        CategoryList.ItemsSource = ConfigUi.Children;
    }
}

// These are in the Configurator.UiCore namespace:

public class ConfiguratorUiItem
{        
    protected string _Key;
    public string Key
    {
        get { return _Key; }
        set { _Key = value; }
    }
}

[ContentProperty("Children")]
public class GroupUiItem : ConfiguratorUiItem
{        
    private ObservableCollection<ConfiguratorUiItem> _Children = new ObservableCollection<ConfiguratorUiItem>();
    public ObservableCollection<ConfiguratorUiItem> Children
    {   get { return _Children; }
        set { _Children = value; }
    }

    private string _UserName;
    public string UserName
    {   get { return _UserName; }
        set { _UserName = value; }
    }
}

public class ParameterUiItem : ConfiguratorUiItem
{
    private string _ParameterType;
    public string ParameterType
    {   
        get { return _ParameterType; }
        set { _ParameterType = value; }
    }

    private string _UserName;
    public string UserName
    {
        get { return _UserName; }
        set { _UserName = value; }
    }
}

【问题讨论】:

    标签: xaml properties


    【解决方案1】:

    好的,我发现了我的问题。菜鸟错误。需要将构建操作设置为无并始终复制。我已将构建操作设置为页面,因此它不是松散的 xaml,也没有更新到适当的文件夹。当我第一次无法解决问题时,我手动将 xaml 文件复制到了输出目录。这导致程序总是使用旧文件。

    当我这样做时,还必须将“;assembly=Configurator”添加到 xmlns 的末尾,以便它现在显示为:“xmlns="clr-namespace:Configurator.UiCore;assembly=Configurator"。然后它起作用了。

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2015-10-03
      • 1970-01-01
      • 2015-12-21
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多