所以我尝试使用以下XAML将TextBlock绑定到ObserverableCollection的Count属性
<TextBlock x:Name="inactiveCount">
<TextBlock.Text>
<Binding Path="(sockets:Manager.inactiveCollection.Count)" Mode="OneWay" StringFormat="Inactive: {0}" />
</TextBlock.Text>
</TextBlock>
但是我在运行程序时收到异常:
Type reference cannot find type named '{clr-namespace:MyProgram.Net.Sockets;assembly=MyProgram}Manager.inactiveCollection'.
绑定到Manager类中的其他属性可以正常工作,而inactiveCollection肯定作为静态属性存在。我究竟做错了什么?
修改
因此,根据fmunkert的建议,我已将其更改为
<TextBlock x:Name="inactiveCount">
<TextBlock.Text>
<Binding Path="Count" Source="(sockets:Manager.inactiveCollection)" Mode="OneWay" StringFormat="Inactive: {0}" />
</TextBlock.Text>
</TextBlock>
它有点工作。它显示错误的计数数字,52当集合中有233个对象在Manager的静态构造函数中初始化时。当对象从集合中删除时,它永远不会更新
修改2
namespace MyProgram.Net.Sockets
{
//technically this is ProxyClientManager but I renamed it here to make the code smaller
class Manager
{
public static ObservableCollection<ProxyClient> inactiveCollection { get; set; }
static Manager()
{
inactiveCollection = new ObservableCollection<ProxyClient>();
//do stuff to populate inactiveCollection with 233 objects
//do other stuff like start threads to add/remove objects from the collection
}
}
}
答案 0 :(得分:1)
使用{x:Static}
作为绑定源,例如像这样:
<TextBlock Text="{Binding Path=Count, Source={x:Static sockets:Manager.inactiveCollection}, Mode=OneWay, StringFormat='Inactive: {0}'}"/>
答案 1 :(得分:0)
所以fmunkert部分正确,我需要指定一个源,但我还需要在Window.Resources中为该类指定一个StaticResource。以下XAML为我工作:
<Window.Resources>
<sockets:Manager x:Key="Manager"/>
</Window.Resources>
<TextBlock x:Name="inactiveCount" Text="{Binding Path='inactiveCollection.Count', Source='{StaticResource Manager}', StringFormat='Inactive: {0}'}"/>