2014-04-21 40 views
0

我確定這很容易,但我不知道它是如何做到的。 我有一個組合框和一個按鈕,只有當組合框有一個選定的項目,即如果在組合框沒有顯示元素時,我需要啓用按鈕,那麼必須禁用按鈕。我怎樣才能做到這一點?綁定按鈕IsEnabled取決於組合框選擇

我曾嘗試做如下:

IsEnabled="{Binding ElementName=mycombobox, Path=SelectedIndex}"/> 

但它不工作。我使用Silverlight 5

在此先感謝

回答

0

MSDN有東西可能對你有幫助here。它建議你使用轉換器或數據觸發器。我沒有測試過,但也許這會起作用?

<Window.Resources> 
    <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}"> 
     <Setter Property="IsEnabled" Value="True"/> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding Path=SelectedItem, ElementName=comboBox1}" Value="{x:Null}"> 
       <Setter Property="UIElement.IsEnabled" Value="False"/> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 

<Grid> 
    <ComboBox Name="comboBox1"> 
     <ComboBoxItem>One</ComboBoxItem> 
     <ComboBoxItem>Two</ComboBoxItem> 
     <ComboBoxItem>Three</ComboBoxItem> 
    </ComboBox> 

    <Button Style="{StaticResource MyButtonStyle}" Name="myButton" Content="Push me"/> 
</Grid> 

編輯

我是Cyndy已經想通了這一切出來的印象,但對於任何未來的讀者......

正如在評論中指出,你不能做DataTriggers在Silverlight中。你需要做一個轉換器。 Here是另一個可能有幫助的帖子。從本質上講,你需要讓你的XAML設置是這樣的:

<Button Content="MyButton" IsEnabled="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource myConverter}}"/> 

,然後在你的後臺代碼,你需要這樣的:

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return !(value == null); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

「{b:EvalBinding [lb.SelectedIndex]> -1}」太棒了!但它不適用於Silverlight ...我正在使用Converter,非常感謝! – Cyndy

+0

答案的這一部分涉及第三方綁定擴展。看看它上面的部分。 – David

+0

好吧,我看,我嘗試在Silverlight中使用它,但有些事情是不同的' '沒有發現Style.Triggers和任何與此類似 – Cyndy

0

有可能是做一個更有效的方式,但我會簡單地確定ComboBox.SelectedItem是否在SelectedIndexChanged事件無效。

+0

是的,這是最簡單的,但我想要在xaml中完成,也許需要一個Converter ...好吧,非常感謝,我評估了這些選擇。問候 – Cyndy

相關問題