【问题标题】:UWP Datagrid Get RowUWP Datagrid 获取行
【发布时间】:2019-12-21 15:26:18
【问题描述】:

如何在 UWP 中获得一行?我在 WPF 中找到了解决方案,但 UWP 似乎没有这些选项。

我不是在问SelectedItem

例如,我有一个显示音乐库的数据网格。我想突出显示正在播放其音乐的行。如何在 c# 或使用 xaml 中做到这一点?

我尝试过使用 Style 和转换器,但我不知道要绑定什么。

DataGrid 的项目源是一个public static List<Music> 对象。

    <controls:DataGrid
        x:Name="MusicLibraryDataGrid"
        Grid.Row="1"
        Margin="10"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        AlternatingRowBackground="WhiteSmoke"
        AlternatingRowForeground="Gray"
        AreRowDetailsFrozen="False"
        AreRowGroupHeadersFrozen="True"
        AutoGenerateColumns="False"
        CanUserReorderColumns="True"
        CanUserResizeColumns="True"
        CanUserSortColumns="True"
        ColumnHeaderHeight="32"
        DoubleTapped="MusicLibraryDataGrid_DoubleTapped"
        Foreground="Black"
        FrozenColumnCount="0"
        GridLinesVisibility="None"
        HeadersVisibility="Column"
        HorizontalScrollBarVisibility="Visible"
        IsDoubleTapEnabled="True"
        IsReadOnly="False"
        ItemsSource="{Binding AllSongs}"
        MinColumnWidth="100"
        SelectionMode="Extended"
        Sorting="MusicLibraryDataGrid_Sorting"
        VerticalScrollBarVisibility="Visible">
        <controls:DataGrid.Columns>
            // Some code
        </controls:DataGrid.Columns>
        <controls:DataGrid.RowStyle>
            <Style TargetType="controls:DataGridRow">
                <Setter Property="Foreground" Value="{Binding Music, Converter={StaticResource DataGridRowColorConverter}}" />
            </Style>
        </controls:DataGrid.RowStyle>
    </controls:DataGrid>

【问题讨论】:

  • 看看这个thread会有帮助
  • @PavelAnikhouski。我认为这仅适用于普通的 Grid 控件,不适用于 DataGrid 控件...
  • 你想要的很难实现。好像没有提供获取每一项的API,所以无法绑定后台。如果你还想实现效果,我推荐你可以使用ListView,然后在viewmodel中用一个属性绑定背景(比如isActive),当你想要高亮背景的时候,设置属性为true,然后使用convert突出显示背景颜色。
  • 听到 WPF 提供了这样的 api 真是令人沮丧...@Faywang-MSFT
  • 是的,为了更好的自定义,最好使用ListView。

标签: c# uwp datagrid


【解决方案1】:

感谢@Faywang - MSFT 的回答here,我意识到,虽然没有直接的方法可以在DataGrid 中获得一行,但解决方法可能是给 ViewModel 一个属性并使用转换器来实现你想要什么。

那个问题提供了一个ListView的例子,但是思路是一样的。

【讨论】:

    【解决方案2】:

    抱歉,回答迟了,但也许它可以帮助未来的人。

    我也遇到过这个问题。我想突出显示一些数据已更改或出现错误的行。

    我发现使用 DataGrid.LoadingRow 事件您可以在该行被实例化之前访问该行并更改一些属性:

    dataGrid.LoadingRow += DataGrid_LoadingRow;
    private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        if ((e.Row.DataContext as string).Length == 0)
                e.Row.Background = new SolidColorBrush(Colors.Blue);
    }
    

    如果行已经实例化并且您无法重新加载它们,那么这个解决方案就没有那么有用了。我希望它可以帮助某人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      相关资源
      最近更新 更多