【问题标题】:DataGrid bound to Collection - add UserControls into one Column绑定到集合的 DataGrid - 将 UserControls 添加到一列中
【发布时间】:2012-03-04 19:49:43
【问题描述】:

我正在编写一个用于传输种子服务器的 GUI。为了保存我的 torrent 信息,我使用 ObservableCollection:

    public partial class Torrents
{
    private static ObservableCollection<Torrent> _list = new ObservableCollection<Torrent>();
    public static ObservableCollection<Torrent> List { get { return _list; } }
}

为了显示种子,我使用绑定到我的 ObservableCollection 的 DataGrid:

<DataGrid x:Name="dataGrid" CanUserReorderColumns="True" AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource TorrentsClass}, Path=List}" CanUserResizeRows="False" CanUserSortColumns="True" IsReadOnly="True" CellStyle="{StaticResource RightAlignment}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="#" Binding="{Binding Path=Id}" />
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
            <DataGridTextColumn Header="Size" Binding="{Binding Path=Size, Converter={StaticResource SizeConverter}}"/>
            <DataGridTextColumn Header="Download Speed" Binding="{Binding Path=DownSpeed, Converter={StaticResource SpeedConverter}}"/>
            <DataGridTextColumn Header="Upload Speed" Binding="{Binding Path=UpSpeed, Converter={StaticResource SpeedConverter}}"/>
            <DataGridTextColumn Header="Ratio" Binding="{Binding Path=Ratio, StringFormat=F2}"/>
        </DataGrid.Columns>
    </DataGrid>

到目前为止一切正常(还不能发布图片):

但为了显示种子状态(无论是暂停、下载、播种、重新检查和上述内容的进度),我想要一个像 uTorrent 一样的进度条:

我创建了一个带有 ProgressBar 和 TextBlock 的自定义 UserControl,它可以工作。

但是如何将 UserControl 添加到 Status 列?以及如何将我的 ObservableCollection 中的数据绑定到它?我想既然它将提供多个数据(进度、具有 torrent 状态的枚举),是否可以将其绑定到具有所述属性的对象?

稍后我将在 DataGrid 中实现上下文菜单以允许暂停选定的种子(还不知道如何......)等等,也许使用 DataGrid 不是最好的主意?如果没有,你有什么建议?

【问题讨论】:

  • 如果有人想知道,我认为 Lars 指的是 WPF .NET 4.0 DataGrid(与 WPF Toolkit Datagrid 相对)。

标签: c# wpf data-binding datagrid user-controls


【解决方案1】:

注意:我假设您使用的是内置的 .NET 4.0 DataGrid


您将需要使用DataGridTemplateColumn。提前采样:

<DataGrid ...>
  <DataGrid.Columns>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <my:MyProgressBar Progress="{Binding Progress}" Text="{Binding Status}" ...>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

我猜了你的属性名称。

【讨论】:

  • 是的,我使用的是内置的 .NET 4.0 DataGrid。你的例子完美地解决了我的问题,干杯!
【解决方案2】:

【讨论】:

  • /facepalm@me 这很明显,我很惭愧;/ 在完成这个项目一整天之后,Head 没有工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多