如何绑定开始鼠标选择的按钮内容

时间:2012-06-04 17:27:53

标签: c# wpf

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="storyboard.clear"
x:Name="Window"
Title="clear"
Width="640" Height="480">

<Grid x:Name="LayoutRoot">
    <Button x:Name="btn_a" Content="A" Height="56" Margin="208,149,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="75" Click="btn_a_Click" />
    <TextBox x:Name="txt_display" Height="50" Margin="208,57,252,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
    <Button x:Name="btn_b" Content="B" Height="56" Margin="297,149,252,0" VerticalAlignment="Top" Click="btn_b_Click" />
</Grid>

public partial class clear : Window
{
    public clear()
    {
        this.InitializeComponent();         

    }

    private void btn_a_Click(object sender, RoutedEventArgs e)
    {
        txt_display.Text += btn_a.Content.ToString();
        txt_display.SelectionStart = txt_display.Text.Length;
        txt_display.Focus();
    }

    private void btn_b_Click(object sender, RoutedEventArgs e)
    {
        txt_display.Text += btn_b.Content.ToString();
        txt_display.SelectionStart = txt_display.Text.Length;
        txt_display.Focus();
    }
}

enter image description here

这里我想绑定鼠标选择开始的按钮内容,如上图所示。

但我无法解决这个问题。

请帮帮我。

2 个答案:

答案 0 :(得分:1)

不确定我是否理解您的问题,但是您是否尝试在文本框中的光标位置插入按钮的内容?如果是这种情况,您需要获取TextBox的插入符索引以确定插入位置。

private void btn_a_Click(object sender, RoutedEventArgs e)
{
    var caretIndex = txt_display.CaretIndex;
    txt_display.Text =txt_display.Text.Insert(caretIndex, btn_a.Content.ToString());
    txt_display.SelectionStart = txt_display.Text.Length;
    txt_display.Focus();
}

答案 1 :(得分:0)

您应该尝试更具体地了解您想要做的事情。假设您有两个按钮,并且您希望其内容与TextBox的插入位置右侧的第一个和第二个字母同步,则可以为TextBox SelectionChanged事件创建一个事件,如下所示:

    private void txtbox_SelectionChanged(object sender, RoutedEventArgs e)
    {
        if (btn != null)
        {
            string letters = txtbox.Text.Substring(txtbox.SelectionStart);

            if (letters.Length > 0)
                btn.Content = letters[0];

            if (letters.Length > 1)
                btn2.Content = letters[1];
        }
    }

在这种情况下,如果你有一个TextBox,里面有文字“Hello World!”插入符号位于 d 的左侧,然后按钮将显示文本“d”和“!”分别