我已经搜索了这个问题的答案,没有运气,我可以看到我已经有了所有正确的元素,但由于某种原因,这不想工作。
我需要在ListBox中选择一个项目时运行IsSelected setter。
XAML代码
<ListBox HorizontalAlignment="Left" Height="226" Margin="10,34,0,0" VerticalAlignment="Top" Width="132" ItemsSource="{Binding Activities}" >
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
C#ViewModel
private bool m_isSelected;
public bool IsSelected
{
get { return m_isSelected; }
set
{
if (value != m_isSelected)
{
m_isSelected = value;
if (m_isSelected)
{
CurrentViews = getCurrentViews((BasePropertyTypeVM)CurrentActivity);
AvailableViews = getAvailableViews(Properties);
}
OnPropertyChanged(() => IsSelected);
}
}
}
非常感谢,
萨姆
答案 0 :(得分:4)
ListBoxItem的IsSelected
属性绑定到IsSelected
视图模型属性,该属性必须是数据项类型的属性,即Activities
集合的元素类型。
您需要声明这样的数据项类,例如
public class Activity : INotifyPropertyChanged
{
public string Name { get; set; }
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
if (value != isSelected)
{
value = isSelected;
...
}
}
}
并声明Activities
这样的集合:
public ObservableCollection<Activity> { get; set; }
可以在ListBoxItem的DataTemplate中使用Activity类的Name
属性:
<ListBox ... ItemsSource="{Binding Activites}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 1 :(得分:0)
试试这个:
<Setter Property="IsSelected" Value="{Binding DataContext.IsSelected,
RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}" />