在 WPF 的 View-Model-ViewModel 模式下,我试图对网格控件的各种定义的高度和宽度进行数据绑定,以便在使用 GridSplitter 后存储用户设置的值。但是,正常模式似乎不适用于这些特定属性。
注意:我将此作为参考问题发布,因为谷歌让我失望了,我不得不自己解决这个问题。我自己的答案要遵循。
在 WPF 的 View-Model-ViewModel 模式下,我试图对网格控件的各种定义的高度和宽度进行数据绑定,以便在使用 GridSplitter 后存储用户设置的值。但是,正常模式似乎不适用于这些特定属性。
注意:我将此作为参考问题发布,因为谷歌让我失望了,我不得不自己解决这个问题。我自己的答案要遵循。
创建IValueConverter
如下:
public class GridLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double val = (double)value;
GridLength gridLength = new GridLength(val);
return gridLength;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
GridLength val = (GridLength)value;
return val.Value;
}
}
然后,您可以在 Binding 中使用转换器:
<UserControl.Resources>
<local:GridLengthConverter x:Key="gridLengthConverter" />
</UserControl.Resources>
...
<ColumnDefinition Width="{Binding Path=LeftPanelWidth,
Mode=TwoWay,
Converter={StaticResource gridLengthConverter}}" />
我发现了一些陷阱:
因此,我使用了以下代码:
private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)
public GridLength HorizontalInputRegionSize
{
get
{
// If not yet set, get the starting value from the DataModel
if (myHorizontalInputRegionSize.IsAuto)
myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel);
return myHorizontalInputRegionSize;
}
set
{
myHorizontalInputRegionSize = value;
if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value)
{
// Set the value in the DataModel
ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value;
}
OnPropertyChanged("HorizontalInputRegionSize");
}
}
和 XAML:
<Grid.RowDefinitions>
<RowDefinition Height="*" MinHeight="100" />
<RowDefinition Height="Auto" />
<RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" />
</Grid.RowDefinitions>
最简单的解决方案是简单地为这些属性使用字符串设置,以便 WPF 使用 GridLengthConverter 自动支持它们,而无需任何额外工作。
另一种可能性,因为您提出了在GridLength
and之间进行转换int
,所以在绑定到 时创建IValueConverter
并使用它Width
。IValueConverter
s 也处理双向绑定,因为它们同时具有ConvertTo()
和ConvertBack()
方法。