【问题标题】:WPF custom control not working as expected in ListviewWPF 自定义控件在 Listview 中未按预期工作
【发布时间】:2017-02-21 12:25:54
【问题描述】:

我想在 Listview 数据模板中放置一个可编辑的文本块自定义控件。我正在关注this article,它运作良好。

但是当我将此控件放在 Listview 数据模板中时,双击文本块时,会触发自定义控件的 OnMouseDoubleClick 事件,但永远不会显示文本框。

我的数据模板:

<DataTemplate x:Key="ItemTemplate">
     <Grid>
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="*" />
             <ColumnDefinition Width="auto" />
         </Grid.ColumnDefinitions>

        <StackPanel Orientation="Horizontal"
                            Grid.Column="0">
            <Image Source="{Binding Icon}"
                           Margin="0 0 4 0" />
            <localp:EditableTextBlock Text="{Binding Tag, Mode=TwoWay}"
                               VerticalAlignment="Center" />
        </StackPanel>
     </Grid>

<ListView
     ItemTemplate={StaticResource ItemTemplate}
     .... />

我不知道为什么 OnMouseDoubleClick EditableTextBlock 被触发,但内部文本框从未按预期显示。

感谢您的帮助,

问候

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    将 TextBlockForegroundColorProperty 和 TextBoxForegroundColorProperty 的默认值从 null 更改为其他值:

    public static readonly DependencyProperty TextBlockForegroundColorProperty = 
       DependencyProperty.Register("TextBlockForegroundColor", 
       typeof(Brush), typeof(EditableTextBlock), new UIPropertyMetadata(Brushes.Black));
    
    public static readonly DependencyProperty TextBoxForegroundColorProperty = 
        DependencyProperty.Register("TextBoxForegroundColor",
        typeof(Brush), typeof(EditableTextBlock), new UIPropertyMetadata(Brushes.Black));
    

    或者在你的 Xaml 中设置它们:

      <local:EditableTextBlock  TextBlockForegroundColor="Black" TextBoxForegroundColor="Black" ... />
    

    编辑

    您可以将键盘焦点设置为 TextBox,但是,您应该将 e.Handled 设置为 true,否则 OnTextBoxLostFocus 将执行并隐藏您的 TextBox。

        protected override void OnMouseDoubleClick(MouseButtonEventArgs e) 
        { 
            base.OnMouseDoubleClick(e);
            this.m_TextBlockDisplayText.Visibility = Visibility.Hidden; 
            this.m_TextBoxEditText.Visibility = Visibility.Visible;
            if (m_TextBoxEditText.IsKeyboardFocusWithin ==false)
            {
                Keyboard.Focus(m_TextBoxEditText);
                e.Handled = true;
               m_TextBoxEditText.CaretIndex = m_TextBoxEditText.Text.Length;
            }
        }
    

    【讨论】:

    • 是的,我之前做过(对不起,如果我没有指定它),因为它是透明的。但问题是一样的:在列表视图中,当我双击 EditableTextBlock 时,永远不会显示文本框。谢谢。
    • 查看我的编辑。如果您没有更改所提供链接中的代码,则此方法有效。
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2018-03-09
    • 2017-01-01
    • 2021-10-22
    • 2015-11-24
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多