我正在尝试做的事情:
<Grid>
<Grid.RowDefinitions>
...
<!--The next line is pseudo code for what I am trying to achieve-->
<RowDefintion Height="if(EditEnabled) { 10* } else { 0 }" />
...
</Grid.RowDefinition>
...
<DockPanel Visibility="{Binding EditEnabled, Converter={StaticResource InverseBooleanToVisibilityConverter}}" ...>
...
我正在尝试根据是否启用编辑来更改 DockPanel 的可见性,同时保持他调整大小并具有固定高度和相对高度的能力。
问题:
是否有一个IValueConverter
(System.Windows.Data.IValueConverter
) 可以接受一个 bool 值和两个数字并选择一个GridLength
基于 bool 值?从检查 IValueConverter
的接口(interface)来看,这似乎不是正确的类型。
或者是否有更好的方法来注入(inject)我想要的 GridLength
?
我尝试过的:
- 查看
IValueConverter
的继承者 - 对我来说没什么明显的 - 将
Height="10*"
移动到DockPanel
标签内并将RowDefinition
更改为Auto
- 这造成了转换异常 - 正在搜索 here
最佳答案
不幸的是,没有执行 if-then 的 IValueConverter
。
(更具体地说:您不能使用 XAML 执行 if-then 逻辑)
但是您可以在 C# 代码中执行 if-then 逻辑。
这是解决方案
public class HeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool enableEdit = (bool)value;
double param = System.Convert.ToDouble(parameter);
if (enableEdit)
return new GridLength(param, GridUnitType.Star);
else
return new GridLength(0);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
还有这样的窗口。
<Window.Resources>
<local:HeightConverter x:Key="heightConverter"/>
<sys:Int32 x:Key="param">10</sys:Int32>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="{Binding Path=EditEnabled, Converter={StaticResource heightConverter}, ConverterParameter={StaticResource param}}" />
</Grid.RowDefinitions>
</Grid>
请考虑同时定义您将使用的所需命名空间,如下所示
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:[your namespace]"
更新 使用IMutliValueConverter 可以获得相同的结果。
public class HeightMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool enableEdit = (bool)values[0];
double param = System.Convert.ToDouble(values[1]);
if (enableEdit)
return new GridLength(param, GridUnitType.Star);
else
return new GridLength(0);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
还有这样的窗口
<Window.Resources>
<local:HeightMultiConverter x:Key="heightMutliConverter"/>
<sys:Int32 x:Key="param">10</sys:Int32>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition >
<RowDefinition.Height>
<MultiBinding Converter="{StaticResource heightMutliConverter}">
<Binding Path="EditEnabled"/>
<Binding Source="{StaticResource param}"/>
</MultiBinding>
</RowDefinition.Height>
</RowDefinition>
</Grid.RowDefinitions>
</Grid>
注意:请不要忘记,您必须通过设置 DataContext
属性来处理 Source
。
关于c# - 是否有 IValueConverter 执行 if-then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997215/