【发布时间】:2016-06-30 09:04:06
【问题描述】:
将 ListBox selectedItem 绑定到我的 ViewModel 需要什么? 视图模型 SelectedClient 始终为空。
通过名为 ClientClickedCommand 的命令成功调用 ClientSelected。但是当我尝试在 ClientSelected 方法中访问视图模型 SelectedClient 时,它的 null 并引发异常。
XAML
<ListBox x:Name="lbSlaves" Width="300" Grid.Row="1" ItemsSource="{Binding Slaves}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectedItem="{Binding SelectedClient, Mode=TwoWay}"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Checked ,Mode=TwoWay}"/>
<Button
Command="{Binding ElementName=MainGrid, Path=DataContext.ClientClickedCommand}"
>
<TextBlock Text="{Binding MachineName, Mode=OneWay}" />
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
VIEVMODEL(绑定到 DataContext)
private MyClient _selectedClient;
public MyClient SelectedClient
{
get {
return _selectedClient;
}
set
{
if (value != _selectedClient)
{
_selectedClient = value;
NotifyPropertyChanged("SelectedClient");
}
}
}
public string _infoText;
public string InfoText {
get {
return _infoText;
}
set {
if (value != _infoText)
{
_infoText = value;
NotifyPropertyChanged("InfoText");
}
}
}
private void ClientSelected()
{
var message = " - " + SelectedClient.MachineName + " was clicked";
InfoText += message;
}
ClientClickedCommand = new Command(ClientSelected, ()=> true);
public ICommand ClientClickedCommand
{
get;
set;
}
更新:我现在尝试像这样通过 CommandParameter 绑定 SelectedClient
<ListBox x:Name="lbSlaves" Width="600" Grid.Row="1"
ItemsSource="{Binding Slaves}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel Orientation="Horizontal" Width="150" Height="60">
<CheckBox IsChecked="{Binding Checked ,Mode=TwoWay}"/>
<TextBlock Text="{Binding MachineName, Mode=OneWay}" />
<Button
Content="Do something"
Command="{Binding ElementName=MainGrid, Path=DataContext.ClientClickedCommand}"
CommandParameter="{Binding ElementName=MainGrid, Path=DataContext.SelectedClient, Mode=TwoWay}" />
<Button Content="Do another thing>" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
【问题讨论】:
-
你是先选择项目然后点击按钮,还是直接点击按钮?
-
我只是单击该项目。我如何选择它们?选择和点击有什么区别?
-
如果你直接点击
DataTemplate中定义的按钮而不选择包含这个按钮的项目,你可能需要一个CommandParameter -
好的,谢谢。所以我再问一次。选择项目和单击按钮内的按钮有什么区别。我想我不明白 WPF 是如何处理这个问题的。
-
在某些时候需要处理鼠标点击。如果按钮处理它,则底层控件不会。