2012-05-09 30 views
0

我現在對標籤按鈕有一個新問題。下面的代碼綁定視圖視圖模型:標籤沒有隱藏在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」之稱,但出於某種原因,圖像始終可見。我需要更改哪些內容才能隱藏它?

+0

是否設置爲初始值隱藏/摺疊? – Alex

+0

我還沒有設置初始值,你的意思是在物業的知名度? – Usher

+0

我的意思是說,默認情況下,您的財產的價值實際上設置爲可見,因此您的標籤最初是可見的。提供其餘代碼是正確的,將_isImageValid初始化爲Hidden或Collapsed應該可以做到。無論如何,你應該接受公認的答案,因爲這是更通用的方法。 – Alex

回答

2

您的問題與實際綁定模式不符,標籤不需要雙向綁定,因爲它通常不會使用設置的來源。

作爲@blindmeis建議,您應該使用轉換器,而不是直接從視圖模型返回Visibility值,還有一個內置於您可以使用的框架中。您還應該確保您的datacontext設置正確,如果不是,那麼標籤將無法綁定到指定的屬性。你是否在同一個窗口上有與視圖模型正確綁定的其他項目?你也應該檢查你的輸出窗口是否有綁定錯誤 - 他們會在那裏被提及。最後,你還應該檢查你的財產是否正確通知 - 這是不可能從你提供的代碼中知道的。

你的控制/窗口應該是這個樣子

<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; 
} 
+0

+1是,懶得給一個轉換器的例子;) – blindmeis

+0

@blindmeis我只是簡單的編輯你的文章來補充一下,但是當我想出我想說的話的時候,它太大了編輯別人的答案。 – slugster

+0

@ slugster,非常感謝。 – Usher

0

嘗試設置綁定模式,雙向

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

不過我不會在一個視圖模型使用System.Windows命名空間。創建一個bool屬性並在綁定中使用一個booltovisibility轉換器。

+0

謝謝blindmeis,即使我通過@shakti在stackoverflow的幫助下得到了這段代碼 – Usher

+0

我試過Mode = TwoWay,似乎沒有工作 – Usher

+0

你確定datacontext設置正確嗎?檢查你的輸出窗口。你的代碼綁定在我的測試項目中工作。 – blindmeis