开发者

Bind focus to datacontext in WPF

I would like to bind the current focu开发者_C百科s to the datacontext. My menu system has a viewmodel that contains a list of ButtonViewModels as datacontext. How would I go about having the focused button be determined by the datacontext?

There is a FocusManager.FocusedElement, but this references to a control and the idea of a ViewModel is to not depend on the implementation of the View...


I tried to place a DataTrigger in the Button Style which binds to a property called IsFocused in the ButtonViewModel and in the Setter Bind FocusManager.FocusedElement to the Button where IsFocused is set to true. This should allow you to Control the Focus directly from the ButtonViewModel

<ItemsControl ItemsSource="{Binding ButtonViewModels}">
    <ItemsControl.Resources>
        <Style x:Key="FocusBindingStyle" TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsFocused}" Value="True">
                    <Setter Property="FocusManager.FocusedElement"
                            Value="{Binding RelativeSource={RelativeSource Self}}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ItemsControl.Resources>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="Test" Style="{StaticResource FocusBindingStyle}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜