【发布时间】:2019-03-20 22:38:10
【问题描述】:
我有一个带有通道对象的 Observable 集合。我尝试将此 Observable Collection 绑定到 DataGrid,如下所示:
XAML:
<DataGrid Grid.Row="1" Grid.ColumnSpan="5" Height="45" Margin="30,10,30,255" ItemsSource="{Binding MGWChannels[0], Source={StaticResource MainWindowViewModel}, Mode=TwoWay}"
AutoGenerateColumns="False" HorizontalAlignment="Stretch" CanUserAddRows="False" RowHeaderWidth="0" >
<DataGrid.Columns>
<DataGridTextColumn Header="Max Retries" Width="auto" Binding="{Binding MGWChannels[0].MaxRetries, Source={StaticResource MainWindowViewModel}}" />
<DataGridTextColumn Header="Backoff Time GW Unreachable" Width="auto" Binding="{Binding MGWChannels[0].BotwUnreachable, Source={StaticResource MainWindowViewModel}}"/>
<DataGridTextColumn Header="Backoff Time GW Busy" Width="auto" Binding="{Binding MGWChannels[0].BotwMGWBusy, Source={StaticResource MainWindowViewModel}}"/>
<DataGridTextColumn Header="Backoff Time GW Error" Width="auto" Binding="{Binding MGWChannels[0].BotwMGWError, Source={StaticResource MainWindowViewModel}}"/>
<DataGridTextColumn Header="Strategy" Width="*"/>
</DataGrid.Columns>
</DataGrid>
ViewModel 中的 Observable 集合:
private ObservableCollection<Channel> _mgwChannels;
public ObservableCollection<Channel> MGWChannels
{
get
{
return this._mgwChannels;
}
set
{
this._mgwChannels = value;
RaisePropertyChanged("MGWChannels");
}
}
不幸的是,它没有像预期的那样工作——因为在 Observable Collection 中有 3 个对象,我想创建 3 个 DataGrid 并将它们与 [0]、[1] 和 [2] 绑定。没有 [0] 它可以工作,但将所有 3 个对象放入列表中,我只想显示每个数据网格的一个对象,而不是所有对象。
为什么它不起作用?我错过了什么?
【问题讨论】:
-
如果您只想单独查看这三个对象,那么将它们放入 ObservableCollection 是没有意义的。我建议使用三个属性并在没有索引器的情况下绑定它们。
-
@MaSiMan 非常感谢您的回答,我认为这应该可行! :)
-
请注意,在 ItemsSource Binding 上设置
Mode=TwoWay是没有意义的。它没有效果。 -
而且 ObservableCollection 当然也毫无意义,因为您显然从不添加或删除元素,或者至少不需要被通知。使用
List<Channel>或IEnumerable<Channel>类型的三个属性,每个属性都包含一个元素。
标签: c# wpf mvvm binding datagrid