【问题标题】:Binding function to textblock in listbox c# WPF将函数绑定到列表框中的文本块 c# WPF
【发布时间】:2015-12-19 02:49:30
【问题描述】:

我正在学习 MVVM,所以它可能是新手问题。

我需要绑定函数:

private void doubleClick(object sender, MouseButtonEventArgs e)

在文本块中:

<Grid>
    <ListBox Name="mediaList" Grid.Row="1"
             ItemsSource="{Binding Medias}"
             IsSynchronizedWithCurrentItem="True">
        <ListBox.ItemTemplate>
            <DataTemplate DataType="{x:Type Models:Media}">
                <StackPanel Orientation="Horizontal">
                    <Image Source="icon-play-128.png" Margin="0,0,5,0" />
                    <TextBlock Text="{Binding Name}" Margin="0,0,5,0">
                        <TextBlock.InputBindings>
                            <MouseBinding Command="{Binding DoubleClick}" Gesture="LeftDoubleClick" />
                        </TextBlock.InputBindings>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

但第一个问题是 DoubleClick 在我的视图模型中,而不是在我的类媒体中(在模型中)。

另一个问题是我需要接收两个参数,我该怎么做?

如果您有更好的方法,请向我解释。

提前致谢。

【问题讨论】:

    标签: c# wpf xaml mvvm listbox


    【解决方案1】:
    1. 要链接 Command 及其 Execute 方法,您可以使用委托。 MSDN 有很好的例子来证明这一点。请参阅那里的示例。

    2. 其次,您实际上是在尝试处理 MouseDoubleClick 事件。但是 MouseDoubleClick 事件是由Control 类公开的。而TextBlock 不是控件。因此,最好将您的 TextBlock 包装在 ContentControl 中。

      <ContentControl MouseDoubleClick="ContentControl_MouseDoubleClick">
              <TextBlock ... />
      </ContentControl>
      

    然后从您的事件处理程序中,以编程方式调用您的命令。

    1. 如果您想保持一切解耦,并且处理该事件非常重要,那么请编写一个行为。在该行为中,您可以附加 MouseDoubleClick 事件处理程序,并做任何您喜欢的事情。您可以在适合您需求的 Behavior 中引入自己的属性。

      using System.Windows.Interactivity;
      
      public class MyBehavior : Behavior<ContentControl>
      { 
           public MyBehavior()
           {}
      
           protected override void OnAttached()
           {
               AssociatedObject.MouseDoubleClick += AssociatedObject_MouseDoubleClick;
               base.OnAttached();
           }
      
           protected override void OnDetaching()
           {
               AssociatedObject.MouseDoubleClick -= AssociatedObject_MouseDoubleClick;
           }
      
           void AssociatedObject_MouseDoubleClick(object sender, MouseButtonEventArgs e)
           {
               // do something
           }
      }
      

    XAML 用法:

    <ContentControl ...
          xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" >
       <TextBlock .../>
       <i:Interaction.Behaviors>
           <local:MyBehavior />       
       </i:Interaction.Behaviors>
    </ContentControl>    
    

    【讨论】:

    • 感谢您的宝贵时间 :)
    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2012-05-09
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多