简体   繁体   中英

Binding converter always return the same value in datatemplate

I have an ItemsControl bound to an ObservableCollection and in the ViewModelBase there is a property called IsVisible.

I have set an DataTemplate for the ItemTemplate of the ItemsControl.

<DataTemplate x:Key="MyDataTemplate">
    <Grid Margin="40,0,50,0" Background="Red" VerticalAlignment="Bottom">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <TextBlock Text="{Binding Category}" 
                   Style="{StaticResource MyTextBolckStyle}"
                   Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>
        <TextBox Grid.Row="1" Width="280"
                 BorderBrush="Black"
                 BorderThickness="2"
                 Height="60"
                 HorizontalAlignment="Left"
                 Text="{Binding IsVisible}"
                 Padding="5,5,0,0"
                 TextWrapping="NoWrap"/>
    </Grid>
</DataTemplate>

and this is the Convert method of my BooleanToVisiblityCoverter

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var val = System.Convert.ToBoolean(value);

        if (val)
        {
            return Visibility.Visible;
        }

        return  Visibility.Collapsed;
    }

and this is the strange result I get:

在此处输入图片说明

As you can see every time the IsVisible property is true, the TextBlock visibility is visible and it works fine but every time the IsVisibe property is false, I expect that the visibility of the TextBlock to be collapsed but it seems to me that it is hidden because there is a white space instead of the TextBlock and since I'm working with silver light and there is no Visibility.Hidden enum there, I really don't know what the problem is and I'm confused.

So please help me on this. Any help is appreciated.

What is your converter definition? There is a BooleanToVisibility converter already added in .NET framework 3.0+

Update:

I tried your code and it works perfectly here. My guess would be that the problem is not in the code you've posted here but somewhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM