WPF curpos in textbox数据绑定到标签

时间:2013-05-17 06:10:38

标签: c# wpf visual-studio-2012

今天早上我遇到了一个小问题,现在因为我对WPF相对较新,我想知道如何做到这一点。

在我的表单上我有一个文本框,我有一个标签,我想实时绑定文本框的当前曲线(当光标移动表更新但仅适用于文本框)。

有没有人知道如何做到这一点?

以下是我在wpf中的文本框的一些示例代码以及我在c#中尝试过的内容。

wpf:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="465" Width="681">
<Grid>
    <ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="405" Margin="10,10,0,0" VerticalAlignment="Top" Width="208" PreviewMouseDown="listbox1_PreviewMouseDown">
        <ListBoxItem Content="Gordon"/>
        <ListBoxItem Content="Nico"/>
        <ListBox.Resources>
            <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}" 
                     Value="True">
                        <Setter Property="IsSelected" Value="True" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.Resources>
    </ListBox>
    <TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="405" Margin="289,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="364" SpellCheck.IsEnabled="True" Cursor="IBeam" AcceptsReturn="True" AllowDrop="True" DragEnter="textbox1_DragEnter" Drop="textbox1_Drop" PreviewMouseUp="textbox1_PreviewMouseUp"/>
    <Label x:Name="label1" Content="" HorizontalAlignment="Left" Margin="241,10,0,0" VerticalAlignment="Top"/>

</Grid>

C#

我的事件在PreviewMouseDown事件

中触发
    private void listbox1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Point curpos = e.GetPosition(textbox1);
        if (listbox1.SelectedItems.Count > 0)
        {
            ListBoxItem mySelectedItem = listbox1.SelectedItem as ListBoxItem;
            if (mySelectedItem != null)
            {
                label1.Content = curpos.ToString();
                DragDrop.DoDragDrop(listbox1, "%" + mySelectedItem.Content.ToString()+"%", DragDropEffects.Copy);
            }                
        }
    }

提前致谢。

1 个答案:

答案 0 :(得分:0)

我添加了以下代码:

    private void textbox1_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        Point curpos = e.GetPosition(textbox1);
        int pos1;
        pos1 = textbox1.GetCharacterIndexFromPoint(curpos, true);
        label1.Content = pos1.ToString();
    }
相关问题