WPF:无法控制我的注意力

时间:2011-04-01 21:21:10

标签: c# wpf events data-binding setfocus

我似乎无法控制住实际的焦点:

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 个答案:

答案 0 :(得分:4)

默认情况下,并非所有UIElements都可以关注,您是否尝试在尝试Focus()之前将Focusable设置为true?

答案 1 :(得分: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

答案 2 :(得分: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;
    }
}