将MySettings与DataGrid列宽进行双向绑定

3
我正在尝试将DataGrid中列的宽度绑定到应用程序设置属性。当绑定模式设置为单向模式时,我已经成功实现了这一点,但是,当应用程序关闭时,需要根据列的宽度更新该设置。当我将绑定模式更改为双向时,绑定完全中断。我的代码如下,如何实现这一点?

enter image description here

扩展类

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>

感谢您提供的出色解决方案。 - Serge P
3个回答

1
问题在于Width是DataGridLength类型,没有默认的转换器可以将其转换为double类型,因此您需要创建自己的转换器来实现转换,下面是一个可行的示例转换器:
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;
    }
}

1

谢谢回复,问题是数据类型不匹配。我只需将设置的数据类型更改为DataGridLength,而无需使用转换器。没有其他改变,一切都正常运行。 再次感谢。

enter image description here


0

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接