小编Sör*_*ren的帖子

如何设置DataGridColumn的宽度以适应内容("Auto"),但是完全填充MVVM中DataGrid的可用空间?

我有一个DataGrid包含一些数据的WPF .我想设置列的宽度,使内容适合并永远不会被裁剪(相反,水平滚动条应该变得可见).另外,我希望DataGrid填充整个地方(我正在使用DockPanel).我使用以下代码(简化):

<DataGrid ItemsSource="{Binding Table}">
    <DataGrid.Columns>
        <DataGridTextColumn MinWidth="100" Width="Auto" Header="Column 1" Binding="{Binding Property1}" />
        <DataGridTextColumn MinWidth="200" Width="Auto" Header="Column 2" Binding="{Binding Property2}" />
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

这显然不是开箱即用的,Width="Auto"因为它总是看起来像这样:

DataGrid:只将行的第一部分标记为

这看起来很丑陋.我想选择整行,或者更好的是填充整个宽度的列,但正如人们所看到的,这不起作用.

如果我Width="*"改用,列的内容会被裁剪掉,这对我来说更糟糕.

我在这里找到了一个类似的问题,并在那里发布了一个解决方法.这可能有效,但我正在使用MVVM模式,因此ItemsSource在ViewModel中得到更新,我无法想到从那里做到这一点的方法,因为我无法访问该ActualWidth属性DataGridColumn.另外,如果可能的话,我只想在XAML中这样做.

我将不胜感激任何帮助.谢谢!

编辑:由于我仍然不知道如何处理它,我开始小小的赏金.关于我可以对我的问题采取什么建议,我会非常高兴.再次感谢!

编辑2:在香肠'回答后,我再次考虑了这些选项.问题是我需要在应用程序运行期间更新WidthMinWidth属性,因此不仅在加载窗口后.我已经尝试过这样的事情了

column.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
column.MinWidth = column.ActualWidth;
column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
Run Code Online (Sandbox Code Playgroud)

在当底层被解雇的一些事件ItemsSource中的DataGrid被更新.然而,这是不行的,因为ActualWidth财产似乎并没有设置后改变WidthAuto.有没有选择以某种方式"重新"它以便ActualWidth …

c# wpf xaml datagrid mvvm

23
推荐指数
2
解决办法
6万
查看次数

如何创建一组行为类似RadioButtons的ToggleButtons?

我正在使用C#和WPF,我基本上想要一些切换按钮,并且只能同时选择其中一个.

我发现了另一个问题,但是那里显示的解决方案不起作用,我不知道为什么.

如果我尝试做在上面的问题中提到的ItemTemplateListBox不适用.我只是没有将切换按钮放入列表框,而是显示为"正常列表框".

我的切换按钮样式如下所示,包含在我的一个资源文件中:

<Style x:Key="ToggleButtonListBox" TargetType="{x:Type ListBox}">
    <Setter Property="ListBox.ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <ToggleButton Content="{Binding}"
                          IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ListBox.ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="BorderThickness" Value="0" />
</Style>
Run Code Online (Sandbox Code Playgroud)

我想直接在XAML代码中添加项目,所以我的代码看起来像

<ListBox Style="{StaticResource ToggleButtonListBox}">
    <ListBoxItem>test1</ListBoxItem>
    <ListBoxItem>test2</ListBoxItem>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

如何创建这样一组按钮?

wpf xaml listbox radio-button togglebutton

14
推荐指数
1
解决办法
1万
查看次数

标签 统计

wpf ×2

xaml ×2

c# ×1

datagrid ×1

listbox ×1

mvvm ×1

radio-button ×1

togglebutton ×1