MouseLeftButtonDown事件不起作用WPF

时间:2018-09-26 18:02:49

标签: c# wpf

大家下午好,我的问题是这个。我试图使事件在单击DataTemplate内的TextBox后被触发,有人能告诉我为什么它不触发事件吗?

遵循下面的代码XAML。

    <StackPanel Orientation="Horizontal">
        <ItemsControl Grid.Row="0" ItemsSource="{Binding Pagamentos}" HorizontalAlignment="Left" x:Name="cbxFormaDePagamento" Margin="0,0,0,8">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBox x:Name="txtFormaPagamento" Text="{Binding FormaPagamento.Nome}" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" Width="216" Height="45" Background="White" BorderThickness="1" BorderBrush="#b7b7b7" IsEnabled="False" FontFamily="Roboto" FontSize="18" Foreground="Black" Padding="0,0,0,0" Margin="0,0,0,8" MouseLeftButtonDown="txtFormaPagamento_MouseLeftButtonDown"></TextBox>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>

MouseLeftButtonDown函数

private void txtFormaPagamento_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var viewModel = DataContext as FormasPagamentoViewModel;

        foreach (var currencyTextBox in FindVisualChildren<CurrencyTextBox>(this))
        {
            if (currencyTextBox.Name == "cbxValor")
            {
                currencyTextBox.Number = viewModel.TotalPagar;
            }
        }
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

原因是由于将ControlTemplate中的子级添加到项控件的顺序。您将看到先将TextBox添加到其中,然后再添加ContentPresenter,这意味着ContentPresenter位于TextBox的顶部。如果允许ContentPresenter参与命中测试,则在单击TextBox时,ContentPresenter正在吃鼠标事件,因此TextBox无法看到它。

因此禁用项控件的内容演示者的IsHitTestVisible属性。 您可以通过向项目控件应用自定义样式来实现。

相关问题