我想在視圖模型中傳遞列表視圖複選框的選定項目,稍後我將使用進一步的過程來存儲在數據庫中。MVVM中的列表視圖複選框的選定項目WPF
在FormWeek.xaml守則
守則FormWeek.xaml.cs
private void SelectDays(object sender, SelectionChangedEventArgs e)
{
(this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);
}
我的視圖模型TaskWeek.cs如下
//聲明
private RelayCommand<object> _checkBoxCommand;
public ObservableCollection<string> CollectionOfDays { get; set; }
public ObservableCollection<string> SelectedItems { get; set; }
public RelayCommand<object> CheckBoxCommand
{
get
{
if (_checkBoxCommand == null)
{
_checkBoxCommand = new RelayCommand<object>((args) => OnCheckBoxCommand(args,true));
// _checkBoxCommand = new RelayCommand(() => OnCheckBoxCommand(object args));
}
return _checkBoxCommand;
}
}
// Con structor
CollectionOfDays = new ObservableCollection<string>();
//方法
private void GetWeekDays()
{
try
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
CollectionOfDays.Add("Saturday");
CollectionOfDays.Add("Sunday");
CollectionOfDays.Add("Monday");
CollectionOfDays.Add("Tuesday");
CollectionOfDays.Add("Wednesday");
CollectionOfDays.Add("Thursday");
CollectionOfDays.Add("Friday");
}));
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskWeek:GetWeekDays");
}
}
public void OnCheckBoxCommand(object obj, bool _direction)
{
try
{
if (SelectedItems == null)
SelectedItems = new ObservableCollection<string>();
if (obj != null)
{
SelectedItems.Clear();
StringBuilder items = new StringBuilder();
if (_direction)
{
foreach (string item in CollectionOfDays)
{
items.AppendFormat(item + ",");
}
}
MessageBox.Show(items.ToString());
}
else
SelectedItems.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "TaskDefinition:OnCheckBoxCommand");
}
}
及以下按鈕點擊commond保存數據。
<Button Grid.Column="2" Grid.Row="2" Content="Save" HorizontalAlignment="Center" VerticalAlignment="Bottom"
Command="{Binding InsertExecDefCommand}" Margin="5" >
現在我的要求是通過選定的列表視圖項目通過命令對象查看模型。我已通過SelectionChanged事件做過FormWeek.xam.cs這個使用下面的代碼作爲
private void OnSelectedItems(object sender, RoutedEventArgs e)
{
StringBuilder items = new StringBuilder();
foreach (string item in checkedListView.SelectedItems)
{
items.AppendFormat(item + ",");
}
string AllDays= items.ToString();
}
但是請讓我知道如何實現通過MVVM這個邏輯。如何在我的視圖模型中獲取選定項目TaskWeek.cs
之後R & D和谷歌我通過RelayCommand完成了chages。在OnCheckBoxCommand方法中,foreach語句是錯誤的,它傳遞所有日子。我只想傳遞選定的listview項目。請建議我在OnCheckBoxCommand方法中出了什麼問題。
請讓我知道在哪裏可以使用CommandHandler。 – Hussain 2013-02-24 13:58:46
CommandHandler是我的自定義類,它實現了ICommand,如果你想使用命令你必須知道這一點,它可以在網上或你可以使用RelayCommand。 – ethicallogics 2013-02-24 14:33:54
謝謝你的想法很有幫助。 – Hussain 2013-03-04 13:17:56