3

我正在尝试将 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

xml

xmlns:w="clr-namespace:Stack"

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

3 回答 3

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;
    }
}
于 2013-09-17T13:04:30.920 回答
1

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

在此处输入图像描述

于 2013-09-17T14:38:52.700 回答
0

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

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

需要注意的另一件事是,在 MSDN 的DataGridColumn.Width 属性页面上,它说:

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;
于 2013-09-17T08:53:59.867 回答