2010-10-23 85 views
2

我有一個關於Control.DataBindings的問題。C#:如何綁定Button.Enabled是否有任何項目選擇ListView

如何將Button.Enabled綁定到是否存在任何選中的ListView?即:

Button.Enabled = ListView.SelectedItems.Count > 0; 

我知道我可以使用ListView.SelectionChanged事件來做到這一點。

我只是想知道如何使用DataBinding來做同樣的工作。

謝謝。

彼得

P.S:我想這樣做的原因是:如果Button.Enabled取決於很多其他控件的條件,我認爲數據綁定是簡單。

+1

你會綁定到?我會像你所建議的那樣使用SelectionChanged事件。 – PaulG 2010-10-23 23:47:52

+0

如果只有它是WPF/Silverlight,它會很容易... – slugster 2010-10-24 00:57:44

回答

1

如果你想使用綁定,你需要創建一個ValueConverter。這是通過實現System.Windows.Data.IValueConverter接口完成的(MSDN頁面有一個示例實現)。如果傳入的int大於0,您將返回true。

對於您的情況,您將綁定Button.EnabledListView.SelectedItems.Count,並指定您的值轉換器。

正如@PaulG在評論中所說,使用SelectionChanged事件可能更容易,但可以通過綁定來完成。

0

我通常先嚐試觸發器,然後是值轉換器。
你實際上並沒有落實在這種情況下,值轉換器,一個簡單的DataTriggger會做:

<Button> 
    <Button.Style> 
    <Style TargetType="{x:Type Button}"> 
     <Style.Setters> 
     <Setter Property="Content" Value="Enabled When Selection Changed"/>   
     </Style.Setters> 
     <Style.Triggers> 
     <DataTrigger Binding="{Binding ElementName=_listBox, Path=SelectedItems.Count}" 
        Value="0"> 
      <Setter Property="IsEnabled" Value="False"/> 
     </DataTrigger> 
     </Style.Triggers> 
    </Style> 
    </Button.Style> 
</Button> 
<ListBox x:Name="_listBox"> 
    <ListBox.Items> 
    <ListBoxItem Content="1"/> 
    <ListBoxItem Content="2"/> 
    </ListBox.Items> 
</ListBox>