Nid*_*ocu 33 data-binding wpf grid column-width row-height
在WPF的View-Model-ViewModel模式下,我试图为网格控件的各种定义的高度和宽度进行数据绑定,因此我可以在使用GridSplitter后存储用户设置它们的值.但是,正常模式似乎不适用于这些特定属性.
注意:我发布这个作为参考问题,我发布谷歌失败了我,我不得不自己解决这个问题.我自己的答案可以遵循.
Gre*_*som 39
创建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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在绑定中使用转换器:
<UserControl.Resources>
<local:GridLengthConverter x:Key="gridLengthConverter" />
</UserControl.Resources>
...
<ColumnDefinition Width="{Binding Path=LeftPanelWidth,
Mode=TwoWay,
Converter={StaticResource gridLengthConverter}}" />
Run Code Online (Sandbox Code Playgroud)
Nid*_*ocu 20
我发现了很多陷阱:
因此,我使用了以下代码:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
和XAML:
<Grid.RowDefinitions>
<RowDefinition Height="*" MinHeight="100" />
<RowDefinition Height="Auto" />
<RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" />
</Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)
小智 7
最简单的解决方案是简单地为这些属性使用字符串设置,以便 WPF 将使用 GridLengthConverter 自动支持它们,而无需任何额外工作。