如何绑定到列表内的元素

时间:2019-07-03 14:12:56

标签: c# wpf xaml binding

我有一个列表,希望绑定到内部值。

public class LogEntryList
{
    public List<LogEntry> LogEntries { get; set; }
    public LogEntryList() { LogEntries = new List<LogEntry>(); }
}
public class LogEntry
{
    public string Name { get; set; }
    public string Data { get; set; }
    public Brush BgColor { get; set; }
    public bool Selected { get; set; }
    public double Type { get; set; }
}
logEntryList.LogEntries.Add(new LogEntry { Name = "Exception 2", Type = 02 });
logEntryList.LogEntries.Add(new LogEntry { Name = "Exception 7", Type = 07 });
<ListBox Grid.Row="1" DataContext="logEntryList">
    <ListBox.ItemsSource>
        <Binding ElementName="logEntryList" Path="LogEntries" Mode="OneWay" />
    </ListBox.ItemsSource>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Background="Purple">
                <TextBlock VerticalAlignment="Center">Name:</TextBlock>
                <TextBlock VerticalAlignment="Center" Margin="5" Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如何将ListBoxItems绑定到Name和Data等值?

1 个答案:

答案 0 :(得分:1)

按照Clemens注释使用Window DataContext解决。

public class LogEntryList
{
    public List<LogEntry> LogEntries { get; set; }
    public LogEntryList() { LogEntries = new List<LogEntry>(); }
}
public class LogEntry
{
    public string Name { get; set; }
    public string Data { get; set; }
    public Brush BgColor { get; set; }
    public bool Selected { get; set; }
    public double Type { get; set; }
}
DataContext = logEntryList;
logEntryList.LogEntries.Add(new LogEntry { Name = "Exception 2", Type = 02 });
logEntryList.LogEntries.Add(new LogEntry { Name = "Exception 7", Type = 07 });
<ListBox Grid.Row="1" Background="DarkGray" ItemsSource="{Binding LogEntries}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock VerticalAlignment="Center" Background="Purple">Name:</TextBlock>
                <TextBlock VerticalAlignment="Center" Margin="5" Text="{Binding Name}" />
                <TextBlock VerticalAlignment="Center" Background="Purple">Name:</TextBlock>
                <TextBlock VerticalAlignment="Center" Margin="5" Text="{Binding Type}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
相关问题