简体   繁体   English

如何将焦点设置在 DataTemplate 的最后一项上?

[英]How is it possible to set the focus on the last item of a DataTemplate?

How is it possible to set the focus (from c#-code behind or xaml itself) to the last item of my DataTemplate?如何将焦点(从后面的 c#-code 或 xaml 本身)设置到我的 DataTemplate 的最后一项?

That is my XAML code:那是我的 XAML 代码:

<ItemsControl x:Name="ListViewItems">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Margin="1 10 0 10" 
                    Height="60">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBox Grid.Column="0"  
                             x:Name="SsidTextBox"
                             Text="{Binding Ssid, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" >
                    </TextBox>
                    <TextBox Grid.Column="1" 
                             x:Name="PasswordTextBox"
                             Text="{Binding Password, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
                    </TextBox>
                </Grid>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

By the way: A new item is generated when I click on a button.顺便说一句:单击按钮时会生成一个新项目。

Thanks!谢谢!

You can use a this attached property:您可以使用此附加属性:

public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool) obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
            "IsFocused", typeof (bool), typeof (FocusExtension),
            new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

    private static void OnIsFocusedPropertyChanged(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement) d;
        if ((bool) e.NewValue)
        {
            uie.Focus(); // Don't care about false values.
        }
    }
}

And then add this to the element you want to focus on:然后将其添加到您要关注的元素中:

 <TextBox Grid.Column="0" local:FocusExtension.IsFocused="{Binding SsidFocus}" x:Name="SsidTextBox" Text="{Binding Ssid, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" ></TextBox>

Thanks for your suggestions but they did not worked for me.感谢您的建议,但它们对我没有用。

But it works to use FocusManager:但它可以使用 FocusManager:

FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"

See also: Set the focus on a textbox in xaml wpf另请参阅: 在 xaml wpf 中将焦点设置在文本框上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM