简体   繁体   中英

Button command in ControlTemplate inside ResourceDictionary

I'm trying to add Command binding to my button in resource dictionary. I have global style designed for the whole app and all I want is add button with command, that openes on-screen keyboard to all textboxes. My code below:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         <Style TargetType="{x:Type TextBox}">
<Setter.Value>
                <ControlTemplate>
                    <Border BorderThickness="0">
                        <StackPanel Orientation="Horizontal">
                            <ScrollViewer Width="150" />
                            <Popup x:Name="icon" IsOpen="False" HorizontalAlignment="Right">
                                <Button BorderThickness="1" Visibility="Visible" Command="{*..and now I want to bind my command...*}">
                                </Button>
                            </Popup>
                        </StackPanel>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="True">
                            <Setter Property="IsOpen" TargetName="icon" Value="True" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Can anyone help to solve the problem?

What you want to do is create a usercontrol containing a textbox with an event handler for the "GotFocus" event starting osk.exe and an event handler "Lostfocus" terminating osk.exe like so:

<UserControl [...] >
    <Grid Background="White">
        <TextBlock GotFocus="ShowKeyboard" LostFocus="HideKeyboard"/>
    </Grid>
</UserControl>

    private void ShowKeyboard(object sender, RoutedEventArgs e)
    {
        //run osk.exe
    }

    private void HideKeyboard(object sender, RoutedEventArgs e)
    {
        //terminate osk.exe
    }

You can bind your button using PlacementTarget

<Button BorderThickness="1" Visibility="Visible" Command="{*..and now I want to bind my command...*}" DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"/>

And later in the code you need to specify the tag, it is looking for window, but you can change the anecestorType.

<TextBox Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

Of Course in your ViewModel(DataContext) you need to have specified correct command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM