0

今天早上我遇到了一个小问题,现在我比较陌生,WPF我想知道如何做到这一点。

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

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

这是我在 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);
            }                
        }
    }

提前致谢。

4

1 回答 1

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();
    }
于 2013-05-17T09:00:43.687 回答