我在项目中使用了以下模板:

<DataTemplate 
    x:Key="textBoxDataTemplate">
    <TextBox 
        Name="textBox"
        ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"
        Tag="{Binding}"
        PreviewKeyDown="cellValueTextBoxKeyDown">
        <TextBox.Text>
            <MultiBinding
                Converter="{StaticResource intToStringMultiConverter}">
                <Binding 
                    Path="CellValue"
                    Mode="TwoWay">
                        <Binding.ValidationRules>
                            <y:MatrixCellValueRule 
                                MaxValue="200" />
                        </Binding.ValidationRules>
                </Binding>
                <Binding 
                    RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type y:MatrixGrid}}" 
                    Path="Tag"
                    Mode="OneWay" />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>
</DataTemplate>

我使用此模板为用户创建可编辑的矩阵。用户能够在矩阵内从一个单元格导航到另一个单元格,我想突出显示所选文本框中的数据,但它不起作用。我调用TextBox.Focus()和TextBox.SelectAll()来实现效果,但没有。 Focus()有效,但文本永远不会突出显示。

欢迎任何帮助和赞赏。

有帮助吗?

解决方案

好的,如果有人有兴趣,我的这个问题的解决方案是在事件处理程序方法中包含语句 e.Handled = true; ,其中 textBox.SelectAll() textBox.Focus()被调用。

问题是我将一个事件处理程序附加到文本框的 PreviewKeyDown 事件中,该事件处理隧道事件,可能还有 SelectAll() Focus()忽略调用而不调用 e.Handled = true; 语句。

希望它能帮到某人。

其他提示

如果没有剩下的代码,很难说这是否适合你,但是我使用你的DataTemplate汇总了一个小样本(减去引用未发布的代码的部分)。

我可以通过向DataTemplate中的TextBox添加GotFocus事件处理程序来选择文本框中的所有文本:

<TextBox 
    ...
    GotFocus="textBox_GotFocus"
    ...>
...
</TextBox>

代码隐藏:

    private void textBox_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            textBox.SelectAll();
        }
    }

如果您尝试在不同情况下选择所有情况(请勿在框获得焦点时),请告诉我。

这是一个非常好的非常简单的解决方案(我不知道它是否适用于您的模板,但请试一试): http://social.msdn.microsoft.com/forums/en-US/wpf/thread/564b5731-af8a-49bf -b297-6d179615819f

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top