在WPF中,我有一個布爾到長度的轉換器,我已綁定到列和行定義。在網格列和行長度上的WPF轉換器僅在沒有使用網格劃分器時才起作用
該轉換器用於讀取綁定的布爾值,以確定行/列是否應該隱藏或顯示。
這樣做是爲了讓我可以「最大化」網格的給定部分或將其返回到其原始大小。只要我不使用網格劃分器來調整大小,這個工作就行了。一旦發生這種情況,它不再設置所需的長度。我有一種感覺,一旦使用分離器,它將刪除列定義上的綁定。有沒有解決這個問題的方法?
轉換
[ValueConversion(typeof(bool), typeof(GridLength))]
public class BoolToGridLengthConverter : IValueConverter
{
public int Length { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value == true) ? new GridLength(Length == 0 ? 1 : Length, GridUnitType.Star) : new GridLength(0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ // Don't need any convert back
return null;
}
}
XAML
<Grid>
<Grid.Resources>
<helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter1" Length="1" />
<helpers:BoolToGridLengthConverter x:Key="BoolToGridLengthConverter2" Length="2" />
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ShowColumn1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="{Binding ShowColumn2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="{Binding ShowColumn3, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="{Binding ShowRow1, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter1}}" />
<RowDefinition Height="5" />
<RowDefinition Height="{Binding ShowRow2, Mode=TwoWay, Converter={StaticResource BoolToGridLengthConverter2}}" />
</Grid.RowDefinitions>
<Grid Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="0"></Grid>
<GridSplitter Grid.Column="0" Grid.ColumnSpan="5" Grid.Row="1" ResizeDirection="Rows" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="5" />
<Grid Grid.Column="0" Grid.Row="2"></Grid>
<GridSplitter Grid.Column="1" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
<Grid Grid.Column="2" Grid.Row="2"></Grid>
<GridSplitter Grid.Column="3" Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="5" />
<Grid Grid.Column="4" Grid.Row="2"></Grid>
</Grid>
編輯:重組問題,包括更多的XAML
編輯:附加信息,當我要擴大網格第一節將所有布爾值設置爲false並將我想要的部分設置爲true。例如,如果我希望最大化Grid.Column 2和Grid.Row 2,我將所有布爾值設置爲false,但ShowColumn2和ShowRow2除外。這可以按預期工作,當布爾值全部設置爲true時,將原始視圖恢復爲原始視圖,它也可以按預期工作。這個問題一旦我使用網格分割器來調整列的大小,它不像以前那樣工作。當我最大化與以前相同的部分時,它可以正常工作,但是當我嘗試調整回原始大小時Grid.Column 2和Grid.Row 2佔據了整個底部行。除此之外的兩列都被最小化了。
這使我相信,當使用網格劃分器時,轉換器將不再能夠將列的值設置爲真。
您可以嘗試根據同一布爾值在列內容(網格,堆疊面板,數據網格等)中使用可見性轉換器。這樣你就不需要GridLength的轉換器。 –
我試過使用可見性轉換器,它沒有調整其他列的大小,它只是使列內容消失。我在想分裂器正在造成這種情況?我在同一視圖中使用可見性轉換器,並按預期工作,但在該網格中沒有網格分割器。 –
@DavidLee,請包含視圖的xaml標記。 – ASh