Установка свойства кнопки на основе IsEnabled, если в списке есть содержимое с BoolConverter в Silverlight? - PullRequest
1 голос
/ 08 марта 2011

Я пытаюсь сделать кнопку включенной, только если в списке есть хотя бы один элемент.Я добавляю списки элементов, выбирая их из списка AutoCompleteBox.Я попытался привязать свойство isEnabled к списку и использовать BoolConverter для проверки, если список содержит содержимое.

<Button x:Name="DisabledButton" Click="RemoveButton_Click" Content="Disabled Button" IsEnabled="{Binding ItemsSource, ElementName=EntitiesListBox,Converter={StaticResource CountToBooleanConverter}}"  />

Я что-то упустил.Мне интересно, если кто-то может сказать мне, что не так.Любые идеи высоко ценятся!

Silverlight XAML:

<UserControl.Resources>
    <local:BoolToOppositeBoolConverter x:Key="CountToBooleanConverter" />
    <local:CountGreaterThanZeroConverter x:Key="CountGreaterThanZeroConverter" />
</UserControl.Resources>

<StackPanel x:Name="LayoutRoot" Background="White" Width="150">
    <TextBlock Text="{Binding ElementName=MyAutoCompleteBox, Path=SelectedItem, TargetNullValue='No item selected', StringFormat='Selected Item: {0}'}" />      
    <sdk:AutoCompleteBox x:Name="MyAutoCompleteBox" IsTextCompletionEnabled="True" ItemsSource="{Binding Items}" />
    <Button x:Name="AddButton" Click="AddButton_Click" Content="AddButton" />
    <Button x:Name="RemoveButton" Click="RemoveButton_Click" Content="RemoveButton" />
    <Button x:Name="DisabledButton" Click="RemoveButton_Click" Content="Disabled Button" IsEnabled="{Binding ItemsSource, ElementName=ListBox,Converter={StaticResource CountToBooleanConverter}}"  />
    <Button x:Name="DisabledButton2" Click="RemoveButton_Click" Content="Disabled Button"  IsEnabled="{Binding ItemsSource.Count, ElementName=ListBox, Converter={StaticResource CountGreaterThanZeroConverter}}" />
</StackPanel>

Код:

public partial class MainPage : UserControl
{
    string currentItemText;
    public ObservableCollection<string> Items
    {
        get;
        private set;
    }

    public MainPage()
    {
        InitializeComponent();
        Items = new ObservableCollection<string>();
        Items.Add("One");
        Items.Add("Two");
        Items.Add("Three");
        Items.Add("Four");
        DataContext = this;
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        currentItemText = MyAutoCompleteBox.SelectedItem.ToString();
        ListBox.Items.Add(currentItemText);
        ApplyDataBinding();
    }
    private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        if (ListBox.SelectedItems != null)
        {
            int count = ListBox.SelectedItems.Count - 1;
            for (int i = count; i >= 0; i--)
            {
                ListBox.Items.Remove(ListBox.SelectedItems[i]);
            }
            ApplyDataBinding();
        }
    }

    private void ApplyDataBinding()
    {
        MyAutoCompleteBox.ItemsSource = null;
    }
}

public class CountGreaterThanZeroConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            return (int)value > 0;  
    }


    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }

    #endregion
    }

1 Ответ

1 голос
/ 08 марта 2011

Почему бы просто не привязать счетчик источника предметов и использовать наблюдаемую коллекцию?

 <Button x:Name="DisabledButton" Click="RemoveButton_Click" Content="Disabled Button" IsEnabled="{Binding ItemsSource.Count, ElementName=ListBox,Converter={StaticResource CountGreaterThanZeroConverter}}"  />


    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        return (int)value > 0;
    }

И в вашей модели просмотра

    public ObservableCollection<string> Items
    {
        get;
        private set;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...