WPF: Не могу получить контроль - PullRequest
2 голосов
/ 02 апреля 2011

Кажется, я не могу получить контроль над фокусом:

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 (я его отслеживал).

Ответы [ 3 ]

4 голосов
/ 02 апреля 2011

Не все UIElements могут быть сфокусированы по умолчанию, вы пробовали установить Focusable в true, прежде чем пытаться Focus()?

1 голос
/ 02 апреля 2011

Мы используем это в нашем приложении:

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

0 голосов
/ 02 апреля 2011

Я не смог воспроизвести вашу проблему, она прекрасно работает со мной, попробуйте следующий код для нового проекта в качестве доказательства концепции и посмотрите, работает ли он с вами:

<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;
    }
}
...