我试图在MVVM中获取ComboBox的值并将其传递给我的ViewModel。
xaml中的我的组合框是..
<ComboBox
DataContext="{StaticResource WorkorderGroups}"
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
Height="20"
ItemsSource="{Binding Path=AllC}"
SelectedItem="{Binding Path=SelectedC, Mode=TwoWay}"
/>
然后在WorkorderView
中设置所选项目 public List<long?> AllC
{
get
{
return _workorderRepository.GetCustomersID();
}
set
{
if (value == _workorderRepository.GetCustomersID())
return;
value = _workorderRepository.GetCustomersID();
base.OnPropertyChanged("AllC");
}
}
public string SelectedC
{
get
{
return item;
}
set
{
item = value;
OnPropertyChanged("SelectedC");
}
}
然后在按钮上单击我试图在AllWorkorderViewModel中访问它,我使用以下代码...
public ICommand Test
{
get
{
if (_test == null)
{
_test = new RelayCommand(
param => this.Testy()
);
}
return _test;
}
}
public void Testy()
{
List<string> s = this.AllWorkorders.Select(C => C.SelectedC).ToList();
string s1 = s[0];
}
请忽略方法名称,这只是草稿代码。
我的问题是它返回的字符串不是所选项目,它是一个包含200多个项目的列表,它们都是空的。有谁知道为什么?
感谢。
答案 0 :(得分:0)
这条线我不明白:
List<string> s = this.AllWorkorders.Select(C => C.SelectedC).ToList();
什么是AllWorkorders
?如果您想要当前所选的项目,那么它本身就是SelectedC
。如果要查找其他列表中的项目,则必须执行var item = AllWorkorders.FirstOrDefault(x => x.YourMatchingProperty == SelectedC)
我不确定您是否理解Select的作用 - 我觉得您想要使用Where / First或Single运算符:查看这些Linq样本:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
答案 1 :(得分:0)
您的ViewModel对我来说看起来不太正确。这里有一个MVVM的工作示例:
MainWindow XAML:
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<ComboBox Width="100" Height="20" ItemsSource="{Binding AllC}" SelectedItem="{Binding SelectedC, Mode=TwoWay}" Margin="20"/>
<Button Width="100" Height="20" Margin="20" Command="{Binding GetValueCombobox}"></Button>
</StackPanel>
</Grid>
MainWindow.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
MainWindowViewModel:
public class MainViewModel : INotifyPropertyChanged
{
private readonly List<long?> _workorderRepositoryList = new List<long?>() {1, 2, 5, 3, 4};
public List<long?> AllC
{
get { return _workorderRepositoryList; }
set
{
if (value == _workorderRepositoryList)
return;
value = _workorderRepositoryList;
OnPropertyChanged("AllC");
}
}
private string item;
public string SelectedC
{
get { return item; }
set
{
item = value;
OnPropertyChanged("SelectedC");
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public ICommand EvaluateStateCommand
{
get
{
return new RelayCommand(parameter =>
{
var myItem = SelectedC;
//your selected item (the value of the combo) is represented by SelectedC
});
}
}
}