【问题标题】:TwoWay Binding MySettings to DataGrid Column WidthDataGrid 列宽的两种方式绑定设置
【发布时间】:2013-09-16 18:20:34
【问题描述】:

我正在尝试将 DataGrid 中列的宽度绑定到应用程序设置属性。当绑定设置为 OneWay 模式时,我可以正常工作,但是,我需要在应用程序关闭时根据列的宽度更新设置。当我将绑定模式更改为 TwoWay 时,绑定会一起中断。我的代码如下,我该如何实现呢?

扩展类

Public Class SettingBindingExtension
    Inherits Binding

    Public Sub New()
        Initialize()
    End Sub

    Public Sub New(ByVal path As String)
        MyBase.New(path)
        Initialize()
    End Sub

    Private Sub Initialize()
        Me.Source = MySettings.[Default]

        'OneWay mode works for the initial grid load but any resizes are unsaved.
        Me.Mode = BindingMode.OneWay

        'using TwoWay mode below breaks the binding...
        'Me.Mode = BindingMode.TwoWay
    End Sub

End Class

xaml

xmlns:w="clr-namespace:Stack"

<DataGrid>
...
    <DataGridTextColumn Header="STACK" 
                        Width="{w:SettingBinding StackColumnWidth}"/>
...
</DataGrid>

【问题讨论】:

  • 感谢出色的解决方案

标签: wpf vb.net xaml binding application-settings


【解决方案1】:

问题是 Width 是 DataGridLength 类型,并且没有默认转换器返回双倍,因此您需要创建自己的转换器来做到这一点,这里是一个应该可以工作的转换器示例:

class LengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DataGridLengthConverter converter=new DataGridLengthConverter();
        var res = converter.ConvertFrom(value);
        return res;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DataGridLength length = (DataGridLength)value ;
        return length.DisplayValue;
    }
}

【讨论】:

    【解决方案2】:

    感谢您的回复,这是一个数据类型问题。我没有使用转换器,而是将设置的数据类型更改为DataGridLength。没有其他任何改变,一切正常。再次感谢。

    【讨论】:

      【解决方案3】:

      DataGridTextColumn.Width 属性绝对可以处理Two Way Binding,所以我只能假设您的自定义Binding 对象导致了这个问题。你说Binding坏了,但你没有告诉我们错误是什么。作为一个简单的测试,尝试将其替换为标准的Binding 类:

      <DataGridTextColumn Header="STACK" Width="{Binding StackColumnWidth}" />
      

      另外需要注意的是,在 MSDN 的 DataGridColumn.Width Property 页面上,它说:

      Width 属性的 DisplayValue 受以下属性约束(如果已设置),按优先顺序排列:

      • DataGridColumn.MaxWidth

      • DataGrid.MaxColumnWidth

      • DataGridColumn.MinWidth

      • DataGrid.MinColumnWidth

      因此,您可能需要确保将这些设置为适当的值。但是,这不会导致您的问题。

      如果您仍然无法获得任何解决方案,如果您引用了DataGrid 控件,则可以尝试在应用程序关闭时手动保存该值:

      int index = dataGrid.Columns.Single(c => c.Header == "STACK").DisplayIndex;
      double width = dataGrid.Columns[index].Width;
      

      【讨论】:

        猜你喜欢
        • 2021-03-01
        • 1970-01-01
        • 2014-11-29
        • 2012-01-29
        • 2011-03-06
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 2012-03-23
        相关资源
        最近更新 更多