【问题标题】:MouseLeftButtonDown event does not work WpfMouseLeftButtonDown 事件不起作用 Wpf
【发布时间】:2018-09-26 18:02:48
【问题描述】:

大家下午好,我的问题是这样的。我试图在单击 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;
            }
        }
    }

谢谢!

【问题讨论】:

  • 当 IsEnabled 属性设置为 True 时,不会触发鼠标事件。你为什么使用禁用的文本框?

标签: c# wpf


【解决方案1】:

原因是因为 ControlTemplate 中的子项添加到项目控件的顺序。您会看到首先向其中添加了 TextBox,然后添加了 ContentPresenter,这意味着 ContentPresenter 位于 TextBox 之上。如果允许 ContentPresenter 参与命中测试,那么当你点击 TextBox 时,ContentPresenter 正在吃掉鼠标事件,因此 TextBox 看不到它。

所以禁用项目控件的内容呈现器的IsHitTestVisible 属性。 您可以通过将自定义样式应用到项目控件来做到这一点。

【讨论】:

  • 我明白了,对吗?
猜你喜欢
  • 1970-01-01
  • 2016-06-22
  • 2013-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多