开发者

Bind focus to datacontext in WPF

开发者 https://www.devze.com 2023-02-12 04:07 出处:网络
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 b

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

精彩评论

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

关注公众号