【发布时间】:2012-04-20 10:19:20
【问题描述】:
我想使用 SelectedItem 将选择设置为代码中的组合框。 我只能通过使用 SelectedValue 让它工作。 SelectedItem 将在堆栈跟踪的顶部抛出空引用异常:
在 AttachedCommandBehavior.CommandBehaviorBinding.Execute()
XAML:
<Window x:Class="MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:acb="clr-namespace:AttachedCommandBehavior;assembly=AttachedCommandBehavior"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ComboBox Name="ComboItems1"
DisplayMemberPath="Value"
SelectedValuePath="Key"
ItemsSource="{Binding Items}"
SelectedValue="{Binding SelectedValue}"
acb:CommandBehavior.Event="SelectionChanged"
acb:CommandBehavior.Command="{Binding Path=SelectionChangedCommand}"
acb:CommandBehavior.CommandParameter="{Binding ElementName=ComboItems1, Path=SelectedItem}" />
<ComboBox Name="ComboItems2"
DisplayMemberPath="Value"
SelectedValuePath="Key"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
acb:CommandBehavior.Event="SelectionChanged"
acb:CommandBehavior.Command="{Binding Path=SelectionChangedCommand}"
acb:CommandBehavior.CommandParameter="{Binding ElementName=ComboItems2, Path=SelectedItem}"/>
</StackPanel>
代码:
Imports AttachedCommandBehavior
公共类 MainWindowViewModel
Private _mainWindowView As MainWindowView
Public Property Items As New List(Of KeyValuePair(Of Integer, String))
Public Property SelectedItem As Nullable(Of KeyValuePair(Of Integer, String))
Public Property SelectedValue As Nullable(Of Integer)
Public Property SelectionChangedCommand As ICommand
Public Sub New()
Items.Add(New KeyValuePair(Of Integer, String)(1, "first item"))
Items.Add(New KeyValuePair(Of Integer, String)(2, "second item"))
Items.Add(New KeyValuePair(Of Integer, String)(3, "third item"))
Dim simpleCommand As SimpleCommand = New SimpleCommand()
simpleCommand.ExecuteDelegate = Sub(selectedItem As Object)
HandleSelectionChanged(selectedItem)
End Sub
SelectionChangedCommand = simpleCommand
SelectedValue = 1
'SelectedItem = Items(1) 'uncomment this to raise the null ref exception
End Sub
Private Sub HandleSelectionChanged(ByRef selectedItem As Object)
If selectedItem IsNot Nothing Then
'Do something
End If
End Sub
结束类
为什么选择项不起作用?
更新:
尼古拉:你的眼光很敏锐。那是由于最后一分钟的复制粘贴工作!
Blindmeis:当然,这是对一个更大的程序的抽象,在该程序中我需要 selectionchanged 事件来执行一些操作。这些命令绑定必须保留(尽管可能需要一些修复)。
问候,
米歇尔
【问题讨论】:
-
尝试将注释掉的行更改为
SelectedValue = 2我感觉你的事件绑定在 SelectionChanged 上 -
什么时候你的 seleteditem 改变了选择的改变,这样你就可以在你的虚拟机中处理而无需命令?还是我错过了什么?
-
ExitMusic:我希望它与 SelectedItem 一起使用,我正在证明 SelectedValue 有效,但 SelectedItem 无效。 SelectedItem 用于 ComboItems2。
-
Blindmeis,正确:命令绑定让我可以直接在视图模型中处理 selectionchanged 事件,而无需在视图中进行管道处理。
标签: wpf binding mvvm selecteditem selectionchanged