【问题标题】:Name property on class, use it for View Sample Data类上的名称属性,用于查看示例数据
【发布时间】:2014-02-07 09:15:23
【问题描述】:

我创建了一个具有此属性的类

public class PromoViewModel
{
   string name;
   // setter getter here...
   string description;
   // setter getter here...
   string img;
   // setter getter here...
}

问题是,当我制作这样的样本数据时

<vm:MainViewModel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:Dmall.ViewModels"
    SampleProperty="Sample Text Property Value">

    <vm:MainViewModel.Promos>
        <vm:PromoViewModel Name="design one" Description="Maecenas praesent accumsan bibendum" Img="Maecenas praesent accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur"/>
        <vm:PromoViewModel Name="design two" Description="Dictumst eleifend facilisi faucibus" Img="Pharetra placerat pulvinar sagittis senectus sociosqu suscipit torquent ultrices vehicula volutpat maecenas praesent"/>
        <vm:PromoViewModel Name="design three" Description="Habitant inceptos interdum lobortis" Img="Accumsan bibendum dictumst eleifend facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat"/>
    </vm:MainViewModel.Promos>

</vm:MainViewModel>

错误来了,因为“名称”是 XAML 的特殊关键字,x:Name 都不起作用。
XAML 设计查看器上出现此结果错误,因为我尝试这样做

{Binding Name}
// this would never exist because in the sample data, name is special attributes keyword not a property of PromoViewModel class and return NullReferenceException

我可以轻松地将 PromoViewModel 类中的 name 属性更改为“Title”并且它可以工作。
但是效率不高。在类上使用属性“名称”并将其用于示例数据的正确方法是什么?

【问题讨论】:

    标签: c# xaml visual-studio-2012 binding windows-phone-8


    【解决方案1】:

    尝试使用{Binding Path=Name},以便显式设置Path 属性。 Path 只是绑定的默认属性,因此在这种情况下,您要确保绑定知道您在谈论 Path 而不是 Name

    以下对我有用:

    XAML:

    <TextBlock Text="{Binding Path=Name}" />
    

    视图模型:

    public class ViewModel
    {
        public string Name { get; set; }
    }
    

    代码隐藏

    ViewModel vm = new ViewModel();
    vm.Name = "Test";
    
    this.DataContext = vm;
    

    【讨论】:

    • 绑定过程没有错误。这里唯一的错误是在示例数据文件中。 Name 是特殊的属性关键字,我不能将它用于我的 name 属性。
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 2012-12-25
    • 2014-09-22
    • 2022-08-16
    • 2017-04-02
    相关资源
    最近更新 更多