簡體   English   中英

如何確定是否選擇了WPF Datagrid項並將其綁定到正確/錯誤結果

[英]How to determine if an WPF Datagrid item is selected, and bind to the true/false result

我覺得這應該很容易,但是我很沮喪。

我正在嘗試使用MVVM將ComboBox.IsEnabled屬性綁定到類似“是否是當前在DataGrid上選擇的項”屬性。 這樣,如果在DataGrid上沒有選擇任何項目,則組合框將被禁用。

是否有一個DataGrid屬性在選擇一個項目時會注冊True / False,還是我需要對SelectedItems.Count屬性做些事情?

在編寫轉換器或自定義屬性之前,我嘗試使用盡可能少的代碼來執行此操作。

我相信沒有內置屬性會說在DataGrid選擇了一項。 相反,你可以綁定一個屬性SelectedItem您的DataGrid和檢查SelectedItemnull

例如:

 <DataGrid
        ItemsSource="{Binding ListOfitems}" 
        SelectedItem="{Binding CurrentItem, Mode=TwoWay}"/> 

然后你的VM

    private object _CurrentItem;
    public object CurrentItem
    {
        get
        {
            return _CurrentItem;
        }
        set

        {
            _CurrentDocument = value;
            NotifyPropertyChanged();
            //Make your logic for your combobox binding.
        }
    }

// xaml

<DataGrid SelectedItem="{Binding SelectedModelItem}"/> 
<ComboBox IsEnabled={Binding IsItemSelected } />

// VM(您將需要在ViewModel中實現INotifyPropertyChanged)

public bool IsItemSelected { get {return null != SelectedModelItem; }

public YourModelType SelectedModelItem{
get{
   return selectedModelItem;
}
set{
   selectedModelItem = value;
   OnPropertyChanged();   
   }
}

我最終使用轉換器來解決上述問題。 謝謝大家的建議。 在執行此操作之前,我只是想確保自己沒有丟失任何屬性。

XAML

<Control.Resources>
    <local:ItemToBoolConverter x:Key="ItemToBoolConverter"/>
</Control.Resources>

 <ComboBox IsEnabled="{Binding ElementName=dataGrid, Path=SelectedItems.Count, Converter={StaticResource ItemToBoolConverter}}">

背后的代碼

public class ItemToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            int? itemCount = value as int?;
            if (itemCount < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        catch { return DependencyProperty.UnsetValue; }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }

}  

視圖

<Window x:Class="..."
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cvt="clr-namespace:TestTelerikColumnFooter"
    Width="300" Height="300" 
    >
<Window.Resources>
    <cvt:SelectionConverter x:Key="SelectionConverter" />
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ComboBox Grid.Row="0" ItemsSource="{Binding Coll1}" IsEnabled="{Binding SelectedPerson, Converter={StaticResource SelectionConverter}}" DisplayMemberPath="FirstName" Margin="6"/>
    <DataGrid Grid.Row="1" IsReadOnly="True" ItemsSource="{Binding Coll2}" SelectedItem="{Binding SelectedPerson}" Margin="6"/>

</Grid>

MainViewmodel:

public class MainViewModel : INotifyPropertyChanged
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public float Val { get; set; }

    }


    private object _selectedPerson;
    public object SelectedPerson
    {
        get { return _selectedPerson; }
        set
        {
            _selectedPerson = value;
            OnPropertyChanged("SelectedPerson");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private bool _isItemSelected;
    public bool IsItemSelected
    {
        get { return _isItemSelected; }
        set
        {
            if (value == _isItemSelected) 
                return;
            _isItemSelected = value;
            OnPropertyChanged("IsItemSelected");
        }
    }


    private ObservableCollection<Person> _coll1;
    public ObservableCollection<Person> Coll1
    {
        get
        {
            return _coll1 ?? (_coll1 = new ObservableCollection<Person>());
        }
    }

    private ObservableCollection<Person> _coll2;
    public ObservableCollection<Person> Coll2
    {
        get
        {
            return _coll2 ?? (_coll2 = new ObservableCollection<Person>());
        }
    } 

    public MainViewModel()
    {
        Coll1.Add(
        new Person
        {
            FirstName = "TOUMI",
            LastName = "Redhouane",
            Val = 12.2f
        });

        Coll1.Add(
        new Person
        {
            FirstName = "CHERCHALI",
            LastName = "Karim",
            Val = 15.3f
        });

        Coll2.Add(
        new Person
        {
            FirstName = "TOUMI",
            LastName = "Djamel",
            Val = 12.2f
        });
        Coll2.Add(
        new Person
        {
            FirstName = "CHERCHALI",
            LastName = "Redha",
            Val = 12.2f
        });
    }


}

主窗口:

 public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}

轉換器:

 public class SelectionConverter : 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM