2010-06-01 34 views
2

我有2列的網格,在第0列列表框,並在主柵格列中的一個副格柵許多其他控件1.WPF結合其他控件的IsEnabled如果一個列表框具有一個選擇項

如果通過綁定在列表框中選擇了某個項目,我只希望啓用該控件(或者可能是可見的)。我嘗試了一個組合框:

IsEnabled="{Binding myList.SelectedIndex}" 

但這似乎並不奏效。

我錯過了什麼嗎?應該像這樣的工作?

感謝

回答

0

嗯,也許它的工作原理與BindingConverter,其各項指標> 0明確地轉換爲true。

+0

雖然索引0對ListBox有效。如果> -1,你需要做true。 – JustABill 2010-06-01 20:56:56

+0

哦,是的,你是對的。我的錯,謝謝。 – DHN 2010-06-01 21:26:45

5

您需要購買此產品的ValueConverterThis article詳細描述了它,但總結是你需要一個實現IValueConverter的公共類。在Convert()方法,你可以做這樣的事情:現在

if(!(value is int)) return false; 
if(value == -1) return false; 
return true; 

,在XAML中,你需要做的:

<Window.Resources> 
    <local:YourValueConverter x:Key="MyValueConverter"> 
</Window.Resources> 

最後,修改你的綁定:

IsEnabled="{Binding myList.SelectedIndex, Converter={StaticResource MyValueConverter}" 

你確定你不是故意

IsEnabled="{Binding ElementName=myList, Path=SelectedIndex, Converter={StaticResource MyValueConverter}" 

雖然?你不能隱式地把元素的名字放在路徑中(除非Window本身就是DataContext,我想)。綁定到SelectedItem並檢查是否爲空也可能更容易,但這實際上只是優先選擇。

哦,如果你不熟悉的備用xmlns聲明,增長你的Window的頂部添加

xmlns:local= 

和VS會提示你輸入的各種可能性。你需要找到你把你所做的valueconverter命名空間相匹配的一個

0

複製粘貼的解決方案:

這個類添加到您的代碼:

public class HasSelectedItemConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value is int && ((int) value != -1); 
    } 

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

爲靜態資源添加轉換器app.xml的在<Application.Resources>部分:

<local:HasSelectedItemConverter x:Key="HasSelectedItemConverter" /> 

現在你可以在你的XAML中使用它:

<Button IsEnabled="{Binding ElementName=listView1, Path=SelectedIndex, 
Converter={StaticResource HasSelectedItemConverter}"/>