如何从事件参数中获取源实例?

时间:2014-01-20 10:54:34

标签: c# wpf

假设我们有一个名为MyClass的类

public class MyClass
{
      public bool MyProperty {get;set;}
}

我将MyClass列表连接到listview(DataContex等)。

为了使MyClass项看起来不错,我在listView资源中定义了一个DataTemplate。

<DataTemplate DataType="x:type local:MyClass">

我为DataTemplate中的每一行添加了一个扩展器。我添加了一个活动。

<Expander IsExpanded="Expander_Expanded_Method">

在代码中我有这种方法 -

private void Expander_Expanded_Method(object sender, RoutedEventArgs e)
{
  // implement
}

我如何获得MyClass项目的实例来改变它的MyProperty值?

我试过用:

private void Expander_Expanded_Method(object sender, RoutedEventArgs e)
{
  (sender as MyClass).MyProperty = something; // doesn't work :-(
  (e.Source as MyClass).MyProperty = something // doesn't work :-(
}

我发誓我为这件事找了几个小时,我没有找到线索......

我也试过(作为B计划)找一个如何通过XAML更改MyClass MyCperty的例子

 IsExpanded={binding Path=MyProperty, Mode ="TwoWays"}

但它也不起作用...... 提前致谢

修改

谢里登建议我将添加更多信息。我会试着让它变得非常简单:

  • 我有一个listView ui
  • 和MyClass的列表
  • 在listView
  • 中插入的MyClass列表
  • 在每个MyClass实例中都有一个MyOtherClass列表
  • MyOtherClass实例也插入listView
  • 所以 - 我们有一个listView,包含2种物品,MyClass&amp; MyOtherClass
  • 在每个MyClass中都有一个扩展器(使用DataTemplate完成......)
  • 我希望扩展器状态(expand / unexpand)能够使当前MyClass中的MyOtherClass项可见/折叠

谢谢!

3 个答案:

答案 0 :(得分:0)

将一个布尔属性IsExpanded添加到MyClass,将扩展器的IsExpanded属性绑定到,MyClass应该实现INotifyPropertyChanged(如果不是)。

public class MyClass
{
      public bool MyProperty {get;set;}
      public bool IsExpanded {get;set;}
      public MyClass()
      {
          PropertyChanged += (s,e) =>
          {
              if (e.PropertyName == "IsExpanded")
                   // change properties
          }
      }
}

<Expander IsExpanded="{Binding IsExpanded}">

答案 1 :(得分:0)

在StackOverflow上提问时,总是一个好主意,可以解释你的总体目标是什么。用户通常会问一件事,但不幸的是,他们经常在试验时走错路,实际上并没有提出正确的问题。如果您只想将数据从Expander.IsExpanded属性绑定到集合的Visiblity属性,那么您可以尝试这样的事情:

<DataTemplate DataType="{x:Type local:MyClass}">
    <Expander Name="Expander">
        <ListBox ItemsSource="{Binding YourCollection}">
            <ListBox.Style>
                <Style>
                    <Setter Property="ListBox.Visibility" Value="Visible" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsExpanded, 
ElementName=Expander}" Value="True">
                            <Setter Property="ListBox.Visibility" Value="Collapsed" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListBox.Style>
        </ListBox>
    </Expander>
</DataTemplate>

答案 2 :(得分:0)

我确保您的DataTemplate正确应用于ListView的ItemTemplate。

<ListView ItemsSource="{Binding MyItems}">
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type MyClass}">
            <Expander IsExpanded="{Binding MyProperty, Mode=TwoWay}">
                <TextBlock>MyClass instance</TextBlock>
            </Expander>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>