もっと詳しく

In this small example i want to show, how DataBinding can be used to toggle a Window’s Topmost property without a single line of code:

First create a WPF Window with a Toolbar and a ToggleButton in it:

<Window x:Class=”TextXUI”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
<Grid>
   <ToolBar>
      <ToggleButton Content=”IsTopMost”></ToggleButton> 
   </Toolbar>
</Grid>
</Window>


Alternatively you can use a CheckBox instead.
Now we need to create a Binding between the ToggleButton’s IsChecked property and the Window’s Topmost property.


<ToggleButton Content=”IsTopMost” 
 IsChecked=”{Binding Path=Topmost, 
 RelativeSource={RelativeSource AncestorType={x:Type Window}}}”>
</ToggleButton>


By using Path=Topmost we define which property should be changed when the IsChecked property changes. Since we have to specify that the TopMost property is part of the Window object, we can use a RelativeSource. The RelativeSource will search for a parent control of Type Window (there will be just one choice). It is also possible to give a Name to the Window and use ElementName=MyWindowName instead of the RelativeSource.
You can now start the application and test the behaviour.