4
比方說,我有一個項目控件綁定到VM上的項目列表。數據模板內部是一個文本框。我如何將焦點設置到XAML或VM中的第一個文本框?將焦點設置爲項目控件中的第1個文本框
在此先感謝您的幫助!在XAML
public static class InitialFocusBehavior
{
public static bool GetFocus(DependencyObject element)
{
return (bool)element.GetValue(FocusProperty);
}
public static void SetFocus(DependencyObject element, bool value)
{
element.SetValue(FocusProperty, value);
}
public static readonly DependencyProperty FocusProperty =
DependencyProperty.RegisterAttached(
"Focus",
typeof(bool),
typeof(InitialFocusBehavior),
new UIPropertyMetadata(false, OnElementFocused));
static void OnElementFocused(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = depObj as FrameworkElement;
if (element == null)
return;
element.Focus();
}
}
然後將其綁定到真正的元素,你要關注:
<ItemsControl ItemsSource="{Binding UsageItems}" Grid.Row="1" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,0,0,3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Month}" Style="{StaticResource Local_MonthLabel}" />
<core:NumericTextBox Value="{Binding Actual, Mode=OneWay}" Style="{StaticResource Local_ActualUsageEntry}" Grid.Column="2"/>
<core:ValidationControl Instance="{Binding Model}" Grid.Column="4" PropertyName="{Binding MonthNumber, StringFormat=AdjustedUsage{0}}">
<core:NumericTextBox Value="{Binding Adjusted}" DefaultValueIfNull="0" Style="{StaticResource Local_AdjustUsageEntry}" x:Name="AdjustmentEntry" inventoryLocationSetup:InitialFocusBehavior.Focus="True" />
</core:ValidationControl>
<telerik:RadComboBox ItemsSource="{Binding Converter={StaticResource Converter_EnumToEnumMemberViewModel}, Mode=OneTime, Source={x:Type Enums:UsageAdjustmentTypes}}" SelectedValue="{Binding Code, Mode=TwoWay}" Grid.Column="6" Style="{StaticResource Local_CodeSelector}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
感謝馬克,我試圖測試一下,但它不喜歡XAML,全是紅色。 「本地:」來自哪裏?對不起,不是XAML開發人員。 :-) – user2041189 2013-05-02 13:34:59
好吧,我試過了,它不起作用。 ItemsControl DataTemplate中的焦點甚至不在控件中,而是位於控件之外的文本框中。它確實彈出到OnElementFocused中,但是它爲每個創建的控件提供了一次該方法(對於它所綁定的項目列表中的每個項目都是1),這導致我相信即使這樣做能夠設置將焦點放在最後一個文本框中,而不是第一個。任何其他想法?我將在下面發佈我的xaml。 – user2041189 2013-05-02 14:04:56
在原始問題中發佈xaml,謝謝。 – user2041189 2013-05-02 14:07:18