[英]WPF - Set propeties of child controls of custom style
我有一個SearchTextBox的自定義樣式。 我在此控件中有多個綁定。
<Style TargetType="{x:Type controls:SearchTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:SearchTextBox}">
<Grid>
<TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding Path=SearchCommand}" Key="Enter" />
<KeyBinding Command="{Binding Path=DeleteSearchCommand}" Key="Esc" />
</TextBox.InputBindings>
</TextBox>
<Button Style="{StaticResource WatermarkButtonCancelStyle}" HorizontalAlignment="Right" Command="{Binding DeleteSearchCommand}" Margin="0,0,22,0"/>
<Button Style="{StaticResource WatermarkButtonSearchStyle}" HorizontalAlignment="Right" Command="{Binding SearchCommand}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我在這里在視圖中使用TextBox:
<controls:SearchTextBox Width="300" HorizontalAlignment="Left" Margin="0,0,0,6" />
如何在我的視圖中而不是在樣式定義中設置綁定。 這樣我就可以在具有不同綁定的多個視圖中使用控件?
自定義TextBox的樣式:
<Style TargetType="{x:Type local:SearchTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:SearchTextBox}">
<DockPanel DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SearchTextBox}}}">
<Button DockPanel.Dock="Right"
Style="{StaticResource WatermarkButtonCancelStyle}"
Command="{Binding DeleteSearchCommand}"/>
<Button DockPanel.Dock="Right"
Style="{StaticResource WatermarkButtonSearchStyle}"
Command="{Binding SearchCommand}"
CommandParameter="{Binding Text}"/>
<TextBox x:Name="InnerTextBox"
Text="{Binding Path=Text}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding SearchCommand}"
CommandParameter="{Binding Text}"
Key="Enter" />
<KeyBinding Command="{Binding DeleteSearchCommand}"
Key="Escape" />
</TextBox.InputBindings>
</TextBox>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
SearchTextBox.cs的代碼:
public class SearchTextBox : TextBox
{
public static readonly DependencyProperty SearchCommandProperty = DependencyProperty.Register(
"SearchCommand", typeof(ICommand), typeof(SearchTextBox), new PropertyMetadata(default(ICommand)));
public SearchTextBox()
{
DeleteSearchCommand = new Command
{
ExecuteHandler = o => Clear()
};
}
public ICommand SearchCommand
{
get { return (ICommand) GetValue(SearchCommandProperty); }
set { SetValue(SearchCommandProperty, value); }
}
public Command DeleteSearchCommand { get; private set; }
}
由於用於清除文本框的命令始終是相同的,因此SearchTextBox包含用於清除文本框的命令。
現在可以在視圖中使用SearchTextBox並僅設置SearchCommand
屬性。
<local:SearchTextBox Height="30" Width="200" SearchCommand="{Binding DoTheSearch}"/>
如您在SearchTextBox的樣式中所看到的,“文本”被設置為SearchCommand的參數,因此您可以在指定命令的地方使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.