2

私は自分のコントロールを実際に焦点を合わせることができないようです:

XAML:

<Button Command={Binding SetGridToVisibleCommand} />
<Grid Visibility="{Binding IsGridVisible, Converter={con:VisibilityBooleanConverter}}">
    <TextBox Text={Binding MyText} IsVisibleChanged="TextBox_IsVisibleChanged" />
</Grid>

XAML.cs:

private void TextBox_IsVisibleChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
    UIElement element = sender as UIElement;

    if (element != null)
    {
        Boolean success = element.Focus(); //Always returns false and doesn't take focus.
    }
}


ViewModelは、IsGridVisibleをtrueに設定する役割を果たし、コンバーターは、その値をVisibility.Visible(スヌープした)に変換することによってその役割を果たします。

4

3 に答える 3

6

UIElementsデフォルトですべてに焦点を合わせることができるわけではありません。Focusable試す前にtrueに設定してみましたFocus()か?

于 2011-04-01T21:38:57.410 に答える
1

これをアプリケーションで使用します。

public static class Initial
{
    public static void SetFocus(DependencyObject obj, bool value)
    {
        obj.SetValue(FocusProperty, value);
    }

    public static readonly DependencyProperty FocusProperty =
            DependencyProperty.RegisterAttached(
             "Focus", typeof(bool), typeof(Initial),
             new UIPropertyMetadata(false, HandleFocusPropertyChanged));

    private static void HandleFocusPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = (UIElement)d;
        if ((bool)e.NewValue)
            element.Focus(); // Ignore false values.
    }
}

そして使用法は次のとおりです。

<TextBox Text="{Binding FooProperty, UpdateSourceTrigger=PropertyChanged}"
         Grid.Column="1" HorizontalAlignment="Stretch"
         Style="{StaticResource EditText}" ui:Initial.Focus="True"/>

元のアイデアはSOから来ましたが、答えを見つけることができませんでした。背後にある100%無料のコード:P

HTH

于 2011-04-01T23:33:44.363 に答える
0

私はあなたの問題を再現できませんでした、それは私とうまく機能しています、概念実証として新しいプロジェクトで次のコードを試して、それがあなたと一緒に機能するかどうかを確認してください:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <Button Content="Click" Click="Button_Click" />
        <Grid>
            <TextBox Name="NameTextBox" Text="ddd"
                     IsVisibleChanged="TextBox_IsVisibleChanged" />
        </Grid>
</StackPanel>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void TextBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = sender as UIElement;

        if (element != null)
        {
            Boolean success = element.Focus(); //Always returns false and doesn't take focus.
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (NameTextBox.IsVisible)
            NameTextBox.Visibility = Visibility.Collapsed;
        else
            NameTextBox.Visibility = Visibility.Visible;
    }
}
于 2011-04-01T21:48:58.023 に答える