父属性上的触发器已更改,但是为特定类型的子级设置了属性

时间:2014-01-21 20:03:54

标签: c# wpf xaml triggers

我不知道这是否可行,我对wpf了解不多。

我有这个TabControl,每个TabItems包含一个TextBox

<TabControl>
        <TabItem Style="{StaticResource TabStyle}" Header="TabItem1">
            <TextBox/>
        </TabItem>
        <TabItem Style="{StaticResource TabStyle}" Header="TabItem2">
            <TextBox/>
        </TabItem>
 </TabControl>

我对TabItem有这种风格

<Style x:Key="TabStyle" TargetType="{x:Type TabItem}">
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="true">
                    <Setter Property="Text" Value="tab is focused"/> <!--Point this setter to the textbox inside the tab item -->
                </Trigger>
                <Trigger Property="IsFocused" Value="false">
                   <Setter Property="Text" Value="tab is focused"/><!--Point this setter to the textbox inside the tab item -->
                </Trigger>
            </Style.Triggers>
   </Style>

如果我的标签项只有一个TextBox类型的控件,是否可以从标签项触发器内的setter修改该文本框,如何在不使用名称的情况下找到TextBox类型的子项?

1 个答案:

答案 0 :(得分:1)

我建议将TabItem的IsFocused属性绑定到ViewModel中的bool属性。我还将TextBox Text属性绑定到ViewModel中的字符串。

<TabControl>
    <TabItem IsFocused="{Binding IsFocused}" Header="TabItem1">
        <TextBox Text="{Binding IsFocusedText}" />
    </TabItem>
</TabControl>

然后,您可以创建一个方法来在TabItem IsFocused时更改TextBox值,如下所示:

public bool _isFocused;
public bool IsFocused
{
   get { return _isFocused; }
   set
   {
      if (value == _isFocused)
         return;
      _isFocused = value;
      OnIsFocusedChanged(value);
      RaisePropertyChanged(() => IsFocused);
}

private void OnIsFocusedChanged(bool isFocused)
{
   if (isFocused)
      IsFocusedText = "tab is focused";
   else
      IsFocusedText = "tab is NOT focused";
}

public bool _isFocusedText;
public bool IsFocusedText
{
   get { return _isFocusedText; }
   set
   {
      if (value == _isFocusedText)
         return;
      _isFocusedText = value;
      RaisePropertyChanged(() => IsFocusedText);
}

修改

另一种选择:

<TabControl>
    <TabItem Name="TabItem1" Header="TabItem1">
        <TextBox Text="tab is NOT focused" >
           <TextBox.Style>
              <Style TargetType="{x:Type TextBox}">
                 <Style.Triggers>
                    <DataTrigger Binding="{Binding IsFocused, ElementName=TabItem1}" Value=True>
                       <Setter Property="Text" Value="tab is focused" />
                    </DataTrigger>
                 </Style.Triggers>
              </Style>
           </TextBox.Style>
         </TextBox>
    </TabItem>
</TabControl>