我的 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 个元素。所以我添加了一些测试,无论可观察集合中有多少项目,标签始终显示值 15:/。输出窗口中也没有显示任何绑定(bind)错误,所以我不知道该怎么做。
我的问题:
- 为什么绑定(bind)表达式的值总是 15?
- 如何编写正确的绑定(bind),以便它始终显示 列表
- 是否可以在不写值的情况下添加一些文本 自己转换?
请您参考如下方法:
您的绑定(bind)源是文字字符串“ActiveComputers”,其中有 15 个字符。因此,您显示的是字符串中的字符数,并且根本没有连接到集合。
试试这个:
Content="{Binding ActiveComputers.Count}"
