Page资源中的DataContext绑定

时间:2018-08-10 09:38:20

标签: wpf data-binding resources datacontext

我有一个页面,该页面在后面的代码中获得了数据上下文对象。 当触发器变量丢失1值时,我想为TextList [11]设置一个空值。触发器“ int”和文本列表“ ObservableCollection”位于Datacontext对象中。在设置页面datacontext之前,将TextList初始化为20pcs元素。我必须在WPF代码中解决它,排除在后面的代码。我的英语很差,很抱歉!

<Page x:Class="LayerTemplates.Templates.example"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:LayerTemplates.Templates"
  mc:Ignorable="d" 
  d:DesignHeight="450" d:DesignWidth="800"
  Title=""
  xmlns:System="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
    <DataTemplate x:Key="myDataTemplate" DataType="{x:Type System:String}">
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=Trigger}" Value="1">
                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <StringAnimationUsingKeyFrames Storyboard.TargetName="Page.DataContext" Storyboard.TargetProperty="TextList[11]" Duration="1">
                                <DiscreteStringKeyFrame KeyTime="0" Value=""></DiscreteStringKeyFrame>
                            </StringAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</Page.Resources>
<Grid>
    ...
</Grid>

1 个答案:

答案 0 :(得分:0)

如果您只想隐藏文本框或标签,请尝试使用样式触发器。当您将字符串的值设置为空值时,我认为您可能可以使用Visibility="Hidden"

在此示例中,我默认情况下隐藏标签,但是每当MyIntProperty变为1时,我都会将可见性更改为“可见”。

我的xaml代码如下:

<Window x:Class="TestBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
    <Label Content="{Binding MyTextProperty}">
        <Label.Style>
            <Style TargetType="Label">
                <Setter Property="Visibility" Value="Hidden"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyIntProperty}" Value="1">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>
</Grid>

数据绑定类和代码隐藏如下:

public class MyViewModel
{
    public int MyIntProperty { get; set; } = 1;
    public string MyTextProperty { get; set; } = "This is my text";
}

public partial class MainWindow : Window
{
    MyViewModel model;
    public MainWindow()
    {
        InitializeComponent();

        model = new MyViewModel();
        this.DataContext = model;
    }
}

请注意,为了使可见性自动更新,您已经让视图模型类为MyIntProperty实现了INotifyPropertyChanged。