2012-03-26 66 views
3

我正在使用MVVM設計模式,並且不希望在我的代碼中留下太多代碼。用XAML和C#編碼。如何在數據綁定文本塊被綁定的屬性發生變化時使用MVVM

當用戶保存一條新記錄時,我想讓「記錄保存」出現在文本塊中然後消失。

這是諸如此類的事情,我想工作:

<TextBlock Name="WorkflowCreated" Text="Record saved"> 
    <TextBlock.Triggers> 
    <DataTrigger Binding="{Binding Path=NewWorkflowCreated}"> 
     <DataTrigger.EnterActions> 
     <BeginStoryboard> 
      <Storyboard> 
       <DoubleAnimation 
       Storyboard.TargetName="WorkflowCreated" 
       Storyboard.TargetProperty="(TextBlock.Opacity)" 
       From="1.0" To="0.0" Duration="0:0:3"/> 
      </Storyboard> 
     </BeginStoryboard> 
    </DataTrigger.EnterActions> 
    </DataTrigger> 
</TextBlock.Triggers> 

所以當NewWorkflowCreated在視圖模型改變,將觸發動畫,不幸的是這是行不通的。我也試過這個:

<TextBlock Name="Message" Text="This is a test."> 
<TextBlock.Triggers> 
    <EventTrigger RoutedEvent="TextBlock.Loaded"> 
    <BeginStoryboard> 
    <Storyboard> 
     <DoubleAnimation 
     Storyboard.TargetName="Message" 
     Storyboard.TargetProperty="(TextBlock.Opacity)" 
     From="1.0" To="0.0" Duration="0:0:3"/> 
    </Storyboard> 
    </BeginStoryboard> 
    </EventTrigger> 
</TextBlock.Triggers> 
</TextBlock> 

任何幫助將不勝感激。也許現在需要View模型中的代碼?

回答

4

拉開動畫你」重新使用一個DataTrigger,它需要一個風格。

<Window.DataContext> 
    <WpfApplication2:TestViewModel/> 
</Window.DataContext> 

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 
    <Grid.Resources> 
     <Style x:Key="textBoxStyle" TargetType="{x:Type TextBlock}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Path=NewWorkflowCreated}" Value="True"> 
        <DataTrigger.EnterActions> 
         <BeginStoryboard> 
          <Storyboard> 
           <DoubleAnimation 
            Storyboard.TargetProperty="(TextBlock.Opacity)" 
            From="1.0" To="0.0" Duration="0:0:3"/> 
          </Storyboard> 
         </BeginStoryboard> 
        </DataTrigger.EnterActions> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Grid.Resources> 
    <TextBlock Name="WorkflowCreated" Style="{StaticResource textBoxStyle}" Text="Record saved" /> 
    <Button Content="press me" Grid.Row="1" Click="Button_Click_1"/> 
</Grid> 

public class TestViewModel : INotifyPropertyChanged 
{ 
    private bool _newWorkflowCreated; 
    public bool NewWorkflowCreated 
    { 
     get { return _newWorkflowCreated; } 
     set { 
      _newWorkflowCreated = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("NewWorkflowCreated")); 
     } 
    } 


    #region Implementation of INotifyPropertyChanged 

    public event PropertyChangedEventHandler PropertyChanged; 

    #endregion 
} 
+0

我永遠感激你的先生。不幸的是,我不能給你任何這方面的投票,但也許有一天... – 2012-03-27 07:24:36

+0

雖然你可以接受答案嗎? – Phil 2012-03-27 07:33:57

0

這種UI特有的行爲一定要在View來處理,而不是ViewModel

我建議尋找到TextChanged事件,看到在那裏

+0

沒有''上TextBlock' TextChanged'事件。綁定聲明中的NotifyOnTargetUpdated是下一個最佳選擇。 – maxp 2015-03-27 15:53:12