将列表从背后的代码绑定到列表框



im试图将列表绑定到列表框,但绝对什么也不会发生。我没有遇到任何错误,但我确定列表框绑定到填充的列表,原因是我有一个文本控件,显示信息中有三个项目。

所以问题是要绑定到listbox

需要什么
<ListBox x:Name="lbSlaves" Width="300" Grid.Row="1"  ItemsSource="{Binding Slaves}" >
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>                    
                <StackPanel Width="150" Height="30"  Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding MachineName}"></TextBox>    <!-- Ive also tried Path=MachineName -->                   
            </DataTemplate>
        </ListBox.ItemTemplate>            
    </ListBox>

背后的代码
public List<ZTClient> Slaves { get; set; } 
     private void SetUpSlaves()
    {

        var client1 = new ZTClient()
        {
            MachineName = "Machine One",
            IpAdress = "34534512",
            Status = "Ready"
        };
        var client2 = new ZTClient()
        {
            MachineName = "Machine Two",
            IpAdress = "123456",
            Status = "Ready"
        };
        var client3 = new ZTClient()
        {
            MachineName = "Machine Three",
            IpAdress = "65464234",
            Status = "Ready"
        };
        AddClient(client1);
        AddClient(client2);
        AddClient(client3);
    //Ive also tried the following
    //lbSlaves.DataContext = Slaves;
        tbInfoBox.Text += "Nr of slaves = " + Slaves.Count() + Slaves[0].MachineName;
    }
    void SetInfoTex(string newText)
    {
        tbInfoBox.Text = newText;
    }
    private void AddClient(ZTClient newClient)
    {
        Slaves.Add(newClient);
    }

默认情况下绑定TwoWay的属性(TextBox.Text)。您的MachineName有一个公共设定器吗?如果不将绑定模式更改为 OneWay,或者更确切地说,使设置器更容易访问以防止绑定错误。

您还可以手动更新信息文本,但是您的ListBox绑定不受更改通知的支持,因此它们可能不会同步。您应该绑定到ObservableCollection<ZTClient>,如果要自行更改实例,则ZTClient类应实现INotifyPropertyChanged

最新更新