2013-05-30 41 views
1

我正在使用WPF(4.5)和Caliburn.Micro。我想了解如何在我的視圖中操作其他控件中的「事件」。我如何讓一個按鈕的Click事件操縱MVVM中的另一個控件

例如:

我查看了Expander控件,一個按鈕和一個GridView。 GridView在擴展器內部。當用戶點擊按鈕時,它調用虛擬機中的一個方法,用一個BindableCollection>>填充gridview。我想要發生的事情是,當那個集合有多於1個項目時,我想自動擴展Expander Control。

想法?

回答

2

您可以綁定到項目集合的數量:

<Expander IsExpanded="{Binding Path=YourCollection.Length, Converter={StaticResource ResourceName=MyConverter}" /> 

,然後在窗口或用戶控件:

<UserControl... xmlns:converters="clr-namespace:My.Namespace.With.Converters"> 
    <UserControl.Resources> 
     <converters:ItemCountToBooleanConverter x:Key="MyConverter" /> 
    </UserControl.Resources> 
</UserControl> 

和轉換器:

namespace My.Namespace.With.Converters { 
    public class ItemCountToBooleanConverter : IValueConverter 
    { 

     // implementation of IValueConverter here 
     ... 
    } 
} 

我寫了這個我的頭,如果它包含錯誤,非常抱歉;)

另請確保您的viewModel實現INotifyPropertyChanged接口,但我假設您已經知道這一點。

+0

很酷,我還沒有與轉換器合作,但我會研究這一點。 –

+0

很高興幫助,它工作? – cguedel

2

@cguedel方法是完全有效的,但如果你不想使用轉換器(爲什麼多一個類),那麼在你的視圖模型中有bool類型的另一個屬性可能稱爲ShouldExpand,那麼爲什麼說這麼多,讓我展示你:

class YourViewModel { 
    public bool ShouldExpand { 
     get { 
      return _theCollectionYouPopulatedTheGridWith.Length() != 0; 
      // or maybe use a flag, you get the idea ! 
     } 
    } 

    public void ButtonPressed() { 
     // populate the grid with collection 
     // NOW RAISE PROPERTY CHANGED EVENT FOR THE ShouldExpand property 
    } 
} 

現在,在您查看使用該綁定,而不是:

<Expander IsExpanded="{Binding Path=ShouldExpand}" /> 

正如我以前說過的其他解決辦法是很好,但我想減少我的解決方案類的數量。這只是另一種方式。

+0

我更喜歡這個 - 無論是你還是你維護一個大型的可重用轉換器庫 – Charleh

相關問題