我有一个ListBox,显示MyObjects的集合.该集合位于ViewModel中.我想处理ListItem上的按钮单击,但绑定有一些麻烦.如果属性绑定到MyObject属性,DataTemplate中的绑定可以正常工作.但是如何将它从ViewModel绑定到属性?
第二个问题我如何使用处理点击事件的代码中的项目信息.例如,我想从项目的TextBox中打印出文本.
代码是这样的:
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<Button Content="{Binding .}"
Command="{Binding ClickCommand}" /> <!--It doesn't work-->
</DataTemplate>
</Window.Resources>
<ListBox x:Name="ListBox"
ItemsSource="{Binding Path=Objects}"
IsSynchronizedWithCurrentItem="True"
ItemTemplate="{StaticResource ItemTemplate}"/>
Run Code Online (Sandbox Code Playgroud)
C#:
public partial class MainWindow : Window
{
VM m_vm;
public MainWindow()
{
m_vm = new VM();
this.DataContext = m_vm;
InitializeComponent();
}
}
public class VM
{
ObservableCollection<string> _objects;
public ObservableCollection<string> Objects
{
get { return _objects; }
set { _objects = value; }
}
public VM()
{
_objects = new ObservableCollection<string>();
Objects.Add("A");
Objects.Add("B");
Objects.Add("C");
} …Run Code Online (Sandbox Code Playgroud) 嗨,我找不到任何类似的问题,所以我发布了新问题。在下面的代码中,我创建带有ListBoxItems的ListBox控件,每个控件内部都包含单选按钮。当我单击单选按钮时,它会被选中,但父级ListBoxItem不会被选中(ListBoxItem未突出显示)。我该如何解决这个问题?
<ListBox Margin="0, 5, 0, 0" ItemsSource="{Binding mySource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- Rabio template -->
<RadioButton GroupName="radiosGroup"
Margin="10, 2, 5, 2"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedSetting}"
CommandParameter="{Binding SomeId, Mode=OneWay}"
Content="{Binding FileNameWithoutExtensions, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)