【发布时间】:2014-08-09 14:49:24
【问题描述】:
当我单击列表框按钮时,我试图从列表框中获取选定的名称。
我的 XAML 页面:-
<ListBox Name="MyListBox" Height="733" ItemsSource="{Binding StudentDetails,Mode=TwoWay}"
HorizontalAlignment="Left" Margin="0,35,0,0"
VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" Padding="5" BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Wheat" BorderThickness="1">
<Image Name="ListPersonImage" Source="{Binding PersonImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,0,0,0"/>
</Border>
<TextBlock Text="{Binding FirstName}" Name="firstName" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<TextBlock Text="{Binding LastName}" Name="lastName" Width="200" Foreground="White" Margin="-200,50,0,0" FontWeight="SemiBold" FontSize="22" />
<TextBlock Text="{Binding Age}" Name="age" Width="200" Foreground="White" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<Button Command="{Binding buttonClick}" DataContext="{Binding DataContext, ElementName=MyListBox}" Margin="-200,0,0,0" Height="80" Width="80">
<Button.Background>
<ImageBrush Stretch="Fill" >
<ImageBrush.ImageSource>
<BitmapImage UriSource="/NewExample;component/Images/icon_increase.png" />
</ImageBrush.ImageSource>
</ImageBrush>
</Button.Background>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Xaml.Cs:-
private void Button_Click(object sender, RoutedEventArgs e)
{
Button myButton = sender as Button;
ListBoxWithButtonModel dataObject = myButton.DataContext as ListBoxWithButtonModel;
int index = MyListBox.Items.IndexOf(dataObject);
MessageBox.Show("Button Clicked" + dataObject.FirstName);
}
在这里我可以在单击按钮时获取所选名称。但是我想从我的视图模型中做同样的事情。请帮我从 ViewModel 中获取选定的名称。
我试过这样。
listButton = new ReactiveAsyncCommand();
listButton.Subscribe(x =>
{
ListBoxWithButtonModel dataObject = listButton.DataContext as ListBoxWithButtonModel;
//int index = MyListBox.Items.IndexOf(dataObject);
MessageBox.Show("Button Clicked" + dataObject.FirstName);
});
但是在这里我收到错误数据上下文不包含 ReactiveAsycCommand。 请帮我解决这个问题。
我的视图模型:-
public ReactiveAsyncCommand buttonClick { get; set; }
public ListBoxWithButtonViewModel()
{
buttonClick = new ReactiveAsyncCommand();
buttonClick.Subscribe(x =>
{
MessageBox.Show("TEst");
});
}
在这里,我可以显示消息框。但是这里怎么获取选中的item呢??
我的另一个尝试。
public RelayCommand<ListBoxWithButtonModel> ItemSelectedCommand { get; private set; }
public ListBoxWithButtonViewModel()
{
ItemSelectedCommand = new RelayCommand<ListBoxWithButtonModel>(ItemSelected);
}
private void ItemSelected(ListBoxWithButtonModel myItem)
{
MessageBox.Show("Testing");
if (null != myItem)
MessageBox.Show("Name==>" + myItem.FirstName);
}
在这里我也无法获取所选项目。请给我任何想法来解决这个问题。
【问题讨论】:
-
您想在视图模型的哪个位置访问选定的名称?
-
@har07.. 我已经更新了我的问题。请查看并给我解决方案。
-
你更新的代码有什么问题,是
myItem总是null吗? -
是的..它总是空的..
标签: c# xaml windows-phone-7 mvvm listbox