WPF Trigger binding to MVVM property

前端 未结 4 878
误落风尘
误落风尘 2020-12-31 11:10

I have a datatemplate containing an image that I want to be hidden if the the value of a property in a ViewModel is true. Can anyone tell me why the the xaml below does not

相关标签:
4条回答
  • 2020-12-31 11:33

    I just did something similar using a ContentControl.

    <ContentControl Content="{Binding CurrentListHasPendingChanges}">
      <ContentControl.ContentTemplate>
        <DataTemplate>
          <Image x:Name="img" Source="..\Images\List_16.png" Margin="0,0,5,0" Visibility="Hidden" />
          <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding}" Value="False">
              <Setter Property="Image.Visibility" Value="Visible" />
            </DataTrigger>
          </DataTemplate.Triggers>
        </DataTemplate>
      </ContentControl.ContentTemplate>
    </ContentControl>
    

    From http://karlhulme.wordpress.com/2007/03/06/using-a-contentcontrol-and-datatemplate-to-indicate-new-andor-modified-data/

    0 讨论(0)
  • 2020-12-31 11:35

    isn't that

    <Setter Property="Visibility" Value="Hidden" />
    

    ?

    I assume you use INotifyProptyChanged.

    EDIT I did some Googling and I think you need to use some sort of template in order to make the trigger work.

    eg.: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/ae2dbfb7-5dd6-4352-bfa1-53634289329d

    http://www.thejoyofcode.com/Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx

    0 讨论(0)
  • 2020-12-31 11:47

    Try removing "Image" part from Property="Image.Visibility" so you'll have:

    <Setter Property="Visibility" Value="Hidden"/>
    

    and add TargetType to your Style:

    <Style TargetType="{x:Type Image}">
    
    0 讨论(0)
  • 2020-12-31 11:57

    In my opinion we not need to use Triggers, with only the Binding it works well. To make binding to a property model, you can use BooleanToVisibilityConverter Is declared as follows:

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </UserControl.Resources>
    

    And how to use it is simple, just point to the key stated above:

    <Image HorizontalAlignment="Left" Height="16"  VerticalAlignment="Center" Width="16" 
           Visibility="{Binding HasError, Converter={StaticResource BooleanToVisibilityConverter}}"
           Source="/myPath;component/Resources/Images/image1.png"/>
    

    The property in the ViewModel:

    private bool _hasError = false;
        public bool HasError
        {
            get { return !string.IsNullOrEmpty(_messageError); }
            set 
            {
                _hasError = value;                
                this.NotifyOfPropertyChange(() => this.HasError);
            }
        }
    
    0 讨论(0)
提交回复
热议问题