标签未在WPF绑定中隐藏

时间:2012-05-09 06:58:37

标签: c# wpf

我现在有一个标签按钮的新问题。下面的代码将视图绑定到视图模型:

<Label Name="isImageValid"  Content="Image not Created" Margin="0,7,1,0" Style="{StaticResource LabelField}"
                Grid.ColumnSpan="2" Grid.Row="15" Width="119" Height="28" Grid.RowSpan="2"
                Grid.Column="1" IsEnabled="True" 
                Visibility="{Binding isImageValid}" />

以下是我的ViewModel代码:

 private System.Windows.Visibility _isImageValid;
 public System.Windows.Visibility isImageValid
        {

            get
            {

                return _isImageValid;
            }
            set
            {


                _isImageValid = value;
               this.RaisePropertyChanged(() => this.isImageValid);

            }
        }
  private void OnImageResizeCompleted(bool isSuccessful)
    {

        if (isSuccessful)
        {

            this.SelectedStory.KeyframeImages = true;
            isImageValid = System.Windows.Visibility.Visible;
        }
        else
        {
            this.SelectedStory.KeyframeImages = false;

        }
    }

标签是为了保持隐藏,直到调用“OnImageResizeCompleted”,但由于某种原因,图像始终可见。我需要改变什么来隐藏它?

2 个答案:

答案 0 :(得分:2)

您的问题不在于实际绑定模式,标签不需要双向绑定,因为它通常不会设置其来源。

正如@blindmeis建议的那样,你应该使用转换器而不是直接从viewmodel返回一个Visibility值,你可以使用一个内置的框架。您还应确保正确设置了datacontext,如果不正确,则标签将无法绑定到指定的属性。您是否在同一窗口中有其他项目正确绑定到viewmodel?您还应检查输出窗口是否存在绑定错误 - 它们将在那里提及。最后,您还应检查您的财产是否正确通知 - 从您提供的代码中无法判断。

你的控件/窗口看起来应该是这样的

<UserControl    x:Class="..."
                x:Name="MyControl"

                xmlns:sysControls="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"

                >   
    <UserControl.Resources> 
        <sysControls:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </UserControl.Resources>

    <Grid>
        <Label  Visibility="{Binding IsImageValid, Converter={StaticResource BooleanToVisibilityConverter}}" />
    </Grid>
</UserControl>

和C#:

public class MyViewModel : INotifyPropertyChanged
{

    public bool IsImageValid 
    {
        get { return _isImageValid; }
        set 
        {
            _isImageValid = value;
            OnPropertyChanged("IsImageValid");
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private bool _isImageValid;
}

答案 1 :(得分:0)

尝试将Binding模式设置为twoway

<Label  Visibility="{Binding isImageValid, Mode=TwoWay}" />

然而,我不会在viewmodel中使用System.Windows命名空间。创建一个bool属性并在绑定中使用booltovisibility转换器。