【问题标题】:Databinding to property of observable collection always shows 15数据绑定到可观察集合的属性总是显示 15
【发布时间】:2012-06-30 02:34:09
【问题描述】:

我的 MainWindow 类中有以下依赖属性(从 WPF 的 Window 继承)

public ObservableCollection<ComputerListItem> ActiveComputers 
        {
            get { return (ObservableCollection<ComputerListItem>)this.GetValue(ActiveComputersProperty); }
            set { this.SetValue(ActiveComputersProperty, value); }
        }

        public static readonly DependencyProperty ActiveComputersProperty = DependencyProperty.Register(
            "ActiveComputers", typeof(ObservableCollection<ComputerListItem>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<ComputerListItem>()));

现在我正在尝试为标签提供 ActiveComputers.Count 的值,所以在我的 XAML 中我有这个:

<Window x:Class="ComputerManagerV3.MainWindow"        
        <!-- SNIP -->
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        >
    <Grid>
       <!--SNIP -->
        <Label Name="labelActive" Content="{Binding Source=ActiveComputers, Path=Count}" ></Label>

即使在设计器中,标签现在显示的值也是 15,这很奇怪,因为列表最初填充了 13 个元素。所以我添加了一些测试,无论 observable 集合中有多少项目,标签总是显示值 15:/。输出窗口中也没有显示绑定错误,所以我不知道该怎么做。

我的问题:

  • 为什么绑定表达式的值总是15?
  • 如何编写正确的绑定,以便它始终显示 列表
  • 是否可以在不写入值的情况下添加一些文本 自己转换?

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    这里有不止一个问题:

    1) 在依赖属性注册中,您将相同的列表实例传递给您的类的所有实例的属性。

    public static readonly DependencyProperty ActiveComputersProperty =
        DependencyProperty.Register(
            "ActiveComputers",
             typeof(ObservableCollection<ComputerListItem>),
             typeof(MainWindow),
             new PropertyMetadata(new ObservableCollection<ComputerListItem>()))
    

    而是使用默认值 null 注册并在类的构造函数中设置属性。

    2) 绑定路径错误。 Source 应该是一条路径。 ElementName 用于从 XAML 中的给定名称开始路径。尝试使用Rachel's suggestion...

    使用RelativeSource而不是DataSource在窗口开始路径,然后使用ActiveComputers.Count作为路径。

    【讨论】:

    • +1 用于查看 PropertyMetadata 的问题,这可能导致一些非常讨厌且难以追踪的错误/
    • 关于问题 2,我没有注意到你做了 DataContext="{Binding RelativeSource={RelativeSource Self}}"。
    【解决方案2】:

    您将Source 属性设置为字符串,而String.Count 是15。

    要正确绑定到属性,请改用这个:

    <Label Name="labelActive" Content="{Binding ActiveComputers.Count, 
         RelativeSource={RelativeSource AncestorType={x:Type Window}}" />
    

    关于你的第三个关于文本格式的问题,你可以使用ContentStringFormat属性来格式化Label的内容

    【讨论】:

    • 感谢 ContentStringFormat 的链接,我知道必须有类似的内置内容。
    【解决方案3】:

    您的绑定源是文字string“ActiveComputers”,其中包含15 个字符。因此,您正在显示字符串中的字符数,并且根本没有连接到集合。

    试试这个:

    Content="{Binding ActiveComputers.Count}"
    

    【讨论】:

    • 啊,我知道如何解决这个问题,但我看不到 15 是从哪里来的。 +1 :)
    • 关于 15 来自哪里的好电话,我真的想不通,最后很明显:/。您对其他问题的建议也很有效。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多