根据项IsSelected属性更改ListBoxItem数据

时间:2011-12-20 09:29:41

标签: wpf datatemplate

我有一个基于ListBox的用户控件。 DataTemplate与Canvas一起显示或隐藏。 当用户点击ListBoxItem时,应该选择它(显示画布) 另一次点击应隐藏画布。

我根据我的数据对象(设备,见下文)使用显示/隐藏画布的转换器

如何根据ListBoxItem IsSelected更改我的数据对象(设备)? (它应该在item select = true和另一个select select = false之间切换)

谢谢,Avi

DataTemplate:

  <DataTemplate x:Key="ItemTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Name}" FontSize="12" Margin="3"/>                    
            <TextBlock Text="{Binding Location}" FontSize="10" Margin="1"/>
            <Canvas x:Name="canvas1" 
                Visibility="{Binding SelectedToggle, Converter={StaticResource MYVisabilityConverter}}"
                IsHitTestVisible="False" >
                <Image Source="/Resources/Images/Bubble.png" Width="100"/>
            </Canvas>

        </StackPanel>                                               

绑定到DataTemplate的对象:

public class Device : Notifier
{

   public Device()
    {          
    }

    public Device(string name)
    {
        this.Name = name;          
    }

    private Point location;
    /// <summary>
    /// the device location
    /// </summary>
    public Point Location
    {
        get { return location; }
        set { location = value; OnPropertyChanged("Location"); }
    }

    string name;
    /// <summary>
    /// the device Name
    /// </summary>
    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }


    bool selectedToggle = false;
    /// <summary>
    /// toggle between select and Un select of the device
    /// </summary>
    public bool SelectedToggle
    {
        get { return selectedToggle; }
        set { selectedToggle = value; OnPropertyChanged("SelectedToggle"); }
    }

}

1 个答案:

答案 0 :(得分:0)

假设您发布的DataTemplate是ListBox的ItemTemplate,您可以使用RelativeSource绑定来获取ListBoxItem的IsSelected

<Canvas x:Name="canvas1" 
        IsHitTestVisible="False"
        Visibility="{Binding 
            RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, 
            Path=IsSelected, 
            Converter={StaticResource MYVisabilityConverter}}">

</Canvas>

如果您希望在ViewModel中保留IsSelected的值,我会为ListBoxItem使用样式设置器。

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="IsSelected" Value="{Binding SelectedToggle}" />
</Style>