ItemsControl内TexBox中的MouseBinding不起作用WPF C#

时间:2018-07-04 12:06:24

标签: c# wpf

我有一个MainWindow,其中有一个EngineersUserControl(Engineers_UC)的ItemsControl以及其他控件。我的Engineers_UC由几个TextBox组成,我想为其添加MouseBinding,以能够在TextBox上单击鼠标左键,并在ViewModel中执行另一个方法。我已经读过,问题可能是ItemsControl的元素不可聚焦,但是我还没有找到解决方案。有什么想法吗?

MainWindow:

 <Grid>
    <StackPanel>
        <UserControl:Ribbon_UC Loaded="Ribbon_UC_Loaded" Margin="0,0,0,70"/>
        <UserControl:Calendar_UC/>
        <ItemsControl ItemsSource="{Binding Engineer}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <UserControl:Engineers_UC />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</Grid> 

Engineers_UC:

 <TextBox Name="EngineerName" IsReadOnly="True" Style="{StaticResource StyleTrigger} Text ="{Binding FULLNAME}">
           <TextBox.InputBindings>
                    <MouseBinding Command="{Binding EngineerCommand}" CommandParameter="{Binding ElementName=EngineerName}" MouseAction="{Binding EngineerCommand.MouseGesture}"/>
                </TextBox.InputBindings>
 </TextBox>

EngineerCommand:

void RelayCommands()
    {
        EngineerCommand = new SimpleDelegateCommand(x => EngineerFunction(x))
        {
            MouseGesture = MouseAction.LeftClick
        };
    }

  void EngineerFunction (object _engineername)
    {
        EngineerNameClicked = (_engineername as TextBox).Text;

    }
public class SimpleDelegateCommand : ICommand
{
    public Key GestureKey { get; set; }
    public ModifierKeys GestureModifier { get; set; }
    public MouseAction MouseGesture { get; set; }

    Action<object> _executeDelegate;

    public SimpleDelegateCommand(Action<object> executeDelegate)
    {
        _executeDelegate = executeDelegate;
    }

    public void Execute(object parameter)
    {
        _executeDelegate(parameter);
    }

    public bool CanExecute(object parameter) { return true; }
    public event EventHandler CanExecuteChanged;
}

1 个答案:

答案 0 :(得分:0)

如果EngineerCommand命令在与将ItemsSource的{​​{1}}属性绑定到(ItemsControl)的集合相同的视图模型类中定义,则您应该在Engineer中将RelativeSource用于绑定:

ItemTemplate