2015-09-14 22 views
1

我有一个通过DataTemplate设置的自定义项目的列表框。在DataTemplate中设置回调方法

<UserControl x:Name="MyMainControl"> 
    <ListBox x:Name="lbConfigurationList" 
      DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
      ItemsSource="{Binding ConfListVM.ObservableConfList}" 
      SelectionChanged="OnConfigurationSelected" 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <local:EditableTextBlock Text="{Binding ConfName}" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</UserControl> 

是否可以调用一个方法在控制拥有此列表框每次成才发生在EditableTextBlock,经过是这样的:

<local:EditableTextBlock Text="{Binding ConfName}" MyNotifyEvent={SomeMyMainControlMethod} /> 

如果这是可能的,我应该寻找到哪些条款了解如何从我的DataTemplate的EditableTextBlock设置和启动事件?
在此先感谢

回答

1

这是一个完整的例子使用行为:

<Window x:Class="TextBlockEventHandlerInDataTemplate.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
    xmlns:local="clr-namespace:TextBlockEventHandlerInDataTemplate" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <ListBox ItemsSource="{Binding items}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBox Text="{Binding ., Mode=TwoWay}" > 
        <i:Interaction.Behaviors> 
          <local:ShowMessageOnTextChangedBehavior/> 
        </i:Interaction.Behaviors> 
       </TextBox> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 

代码隐藏,对不起,我没有时间MVVM方法:

public partial class MainWindow : Window 
{ 
    public ObservableCollection<string> items { get; set; } 

    public MainWindow() 
    { 
     InitializeComponent(); 

     items = new ObservableCollection<string>(); 
     items.Add("item 1"); 
     items.Add("item 2"); 
     items.Add("item 3"); 
     items.Add("item 4"); 

     this.DataContext = this; 
    } 
} 

这应该是你的班级做这项工作:

public class ShowMessageOnTextChangedBehavior : Behavior<TextBox> 
{ 
    protected override void OnAttached() 
    { 
     AssociatedObject.TextChanged += AssociatedObjectOTextChanged; 
     base.OnAttached(); 
    } 

    protected override void OnDetaching() 
    { 
     AssociatedObject.TextChanged -= AssociatedObjectOTextChanged; 
     base.OnDetaching(); 
    } 

    private void AssociatedObjectOTextChanged(object sender, RoutedEventArgs routedEventArgs) 
    { 
     MessageBox.Show(AssociatedObject.Text); 
    } 
} 

另一件事是定义一个附加属性。我使用这两种方式,视心情:)

啊,我是快要忘记一件重要的事情:你需要从引用

Microsoft.Expression.InteractionsSystem.Windows.Interactivity Expression.Blend.SDK。

+0

base.OnDetaching()是否调用Window的OnDetaching()方法? – user1722791

+0

当XAML解析器解析XAML并创建行为实例并将其添加到作为DependencyAttached属性公开的目标控件的BehaviorCollection时,OnAttached被调用,并且它将在窗口关闭时分离。 –

+0

明白了;所以每次引发“TextChanged”事件时都会调用“AssociatedObjectOTextChanged”方法? – user1722791