C# 如何从ViewModel(WPF)引用UI元素?

C# 如何从ViewModel(WPF)引用UI元素?,c#,wpf,C#,Wpf,这对你们来说可能很简单,但我刚刚开始学习WPF,我的思维总是以Winforms为基础,我一直都是错的 不管怎么说,这就是我的情况。我的视图中有如下标签: UserControl <UserControl.Resources> <Converters:BooleanToVisibilityConverter x:Key="visibilityConverter"></Converters:BooleanToVisibilityConverter>

这对你们来说可能很简单,但我刚刚开始学习WPF,我的思维总是以Winforms为基础,我一直都是错的

不管怎么说,这就是我的情况。我的视图中有如下标签:

UserControl

 <UserControl.Resources>

    <Converters:BooleanToVisibilityConverter x:Key="visibilityConverter"></Converters:BooleanToVisibilityConverter>

    <!-- Error Handling -->
    <Converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

    <Converters:ErrorConverter x:Key="errorConverter"/>
    <ControlTemplate x:Key="ErrorTemplate">
        <Border BorderBrush="Red" BorderThickness="2">
            <AdornedElementPlaceholder />
        </Border>
    </ControlTemplate>
    <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors), Converter={StaticResource errorConverter}}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="comboBoxInError" TargetType="{x:Type ComboBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors), Converter={StaticResource errorConverter}}"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>
UserControl
标签


我试图在视图模型中调用此标签,但不确定如何调用

我在viewmodel中没有以下方法,计划使用标签根据如下条件显示一些消息

  ViewModel

 public class MetadataViewModel : NotificationObject, IMetadataViewModel
{
    #region :: Properties ::

    private IEventAggregator eventAggregator;
    private IImageResizerService imageResizer;

    private string headerInfo;
    public string HeaderInfo
    {
        get
        {
            return headerInfo;
        }
        set
        {
            if (this.headerInfo != value)
            {
                this.headerInfo = value;
                this.RaisePropertyChanged(() => this.HeaderInfo);
            }
        }
    }

    public ICommand SaveCommand
    {
        get;
        private set;
    }

    public ICommand CloseCommand
    {
        get;
        private set;
    }

    public ICommand DeleteCommand
    {
        get;
        private set;
    }

    public ICommand SubmitCommand
    {
        get;
        private set;
    }

    public ICommand UnSubmitCommand
    {
        get;
        private set;
    }

    public ICommand LocationSearchCommand
    {
        get;
        private set;
    }

    public ICommand SubjectSearchCommand
    {
        get;
        private set;
    }

    public ICommand RemoveLocationCommand
    {
        get;
        private set;
    }

    public ICommand RemoveSubjectCommand
    {
        get;
        private set;
    }

    private StoryItem selectedStory;
    public StoryItem SelectedStory
    {
        get
        {
            return this.selectedStory;
        }
        set
        {
            if (this.selectedStory != value)
            {
                this.selectedStory = value;
                this.RaisePropertyChanged(() => this.SelectedStory);

                // raise dependencies
                this.RaisePropertyChanged(() => this.CanSave);
                this.RaisePropertyChanged(() => this.CanUnSubmit);
                this.RaisePropertyChanged(() => this.CanDelete);

            }
        }
    }


    public List<Program> ProgramList 
    { 
        get; 
        private set; 
    }

    public List<Genre> GenreList 
    { 
        get; 
        private set; 
    }

    public List<Copyright> CopyrightList 
    { 
        get; 
        private set; 
    }

    public bool CanSave
    {
        get
        {
            bool canSave = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (!this.SelectedStory.Submitted)
                {
                    canSave = true;
                }
            }

            return canSave;
        }
    }

    public bool CanDelete
    {
        get
        {
            bool canDelete = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (!this.SelectedStory.Submitted)
                {
                    canDelete = true;
                }
            }

            return canDelete;
        }
    }



    public bool CanUnSubmit
    {
        get
        {
            bool canUnSubmit = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (this.SelectedStory.Submitted)
                {
                    canUnSubmit = true;
                }
            }

            return canUnSubmit;
        }
    }

    #endregion

    #region :: Contructor ::

    [ImportingConstructor]
    public MetadataViewModel(
            IMetadataController metadataController, 
            IGatewayService gateway, 
            INavigationService navigator,
            IImageResizerService imageResizer,
            IEventAggregator eventAggregator
        )
    {
        this.eventAggregator = eventAggregator;
        this.imageResizer = imageResizer;

        // populate drop-down lists
        this.ProgramList = gateway.GetPrograms(true);
        this.GenreList = gateway.GetGenres();
        this.CopyrightList = gateway.GetCopyrights();

        // add dummy values so the user can de-select
        this.ProgramList.Add(new Program());
        this.GenreList.Add(new Genre());
        this.CopyrightList.Add(new Copyright());

        // commands
        this.SaveCommand = metadataController.SaveCommand;
        this.CloseCommand = metadataController.CloseCommand;
        this.DeleteCommand = metadataController.DeleteCommand;
        this.SubmitCommand = metadataController.SubmitCommand;
        this.UnSubmitCommand = metadataController.UnSubmitCommand;



        this.LocationSearchCommand = new DelegateCommand<string>(this.LocationSearch);
        this.SubjectSearchCommand = new DelegateCommand<string>(this.SubjectSearch);
        this.RemoveLocationCommand = new DelegateCommand<Topic>(this.RemoveLocation);
        this.RemoveSubjectCommand = new DelegateCommand<Topic>(this.RemoveSubject);

        // events
        this.eventAggregator.GetEvent<StorySelectedEvent>().Subscribe(OnStorySelected, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<AddLocationEvent>().Subscribe(OnAddLocation, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<AddSubjectEvent>().Subscribe(OnAddSubject, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<CommandCompletedEvent>().Subscribe(OnCommandCompleted, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<ImageResizeCompletedEvent>().Subscribe(OnImageResizeCompleted, ThreadOption.UIThread);

        this.Initialize();
    }

    #endregion

    private void OnStorySelected(StoryItem selectedStory)
    {
        if (this.selectedStory != null)
        {
            this.Initialize();

            // override the initialized values
            this.SelectedStory = selectedStory;
            this.SelectedStory.HaveChanged = false;
            this.HeaderInfo = "Edit";
        }
    }

    public void OnAddLocation(Topic topic)
    {
        if (topic != null)
        {
            if (!this.SelectedStory.Locations.Contains(topic))
            {
                this.SelectedStory.Locations.Add(topic);
                this.RaisePropertyChanged(() => this.SelectedStory.Locations);
            }
        }
    }

    public void OnAddSubject(Topic topic)
    {
        if (topic != null)
        {
            if (!this.SelectedStory.Subjects.Contains(topic))
            {
                this.SelectedStory.Subjects.Add(topic);
                this.RaisePropertyChanged(() => this.SelectedStory.Subjects);
            }
        }
    }

    private void OnCommandCompleted(string commandType)
    {
        if (commandType == CommandTypes.MetadataEntry)
        {
            this.Initialize();
        }
    }

    private void OnImageResizeCompleted(bool isSuccessful)
    {
        IsImageValid = false;
        if (isSuccessful)
        {

            this.SelectedStory.KeyframeImages = true;
            IsImageValid = true;
        }
        else
        {
            this.SelectedStory.KeyframeImages = false;
            IsImageValid=false;
        }
    }

    private void Initialize()
    {
        this.SelectedStory = new StoryItem();
        this.HeaderInfo = "Create";
    }

    private void LocationSearch(object topicType)
    {
        this.eventAggregator.GetEvent<LocationSearchEvent>().Publish(null);
    }

    private void SubjectSearch(object topicType)
    {
        this.eventAggregator.GetEvent<SubjectSearchEvent>().Publish(null);
    }

    private void RemoveLocation(Topic selected)
    {
        if (selected != null)
        {
            // remove the primary too
            if (this.SelectedStory.PrimaryLocation != null)
            {
                if (string.Equals(this.SelectedStory.PrimaryLocation.FullName, selected.FullName, StringComparison.InvariantCultureIgnoreCase))
                {
                    this.SelectedStory.PrimaryLocation = new Topic();
                }
            }

            bool isSuccessful = this.SelectedStory.Locations.Remove(selected);
            if (isSuccessful)
            {
                this.RaisePropertyChanged(() => this.SelectedStory.Locations);
            }
        }
    }

    private void RemoveSubject(Topic selected)
    {
        if (selected != null)
        {
            // remove the primary too
            if (this.SelectedStory.PrimarySubject != null)
            {
                if (string.Equals(this.SelectedStory.PrimarySubject.FullName, selected.FullName, StringComparison.InvariantCultureIgnoreCase))
                {
                    this.SelectedStory.PrimarySubject = new Topic();
                }
            }

            bool isSuccessful = this.SelectedStory.Subjects.Remove(selected);
            if (isSuccessful)
            {
                this.RaisePropertyChanged(() => this.SelectedStory.Subjects);
            }
        }
    }
}

        private booly _isImageValid;

        public bool IsImageValid
        {
        get
        { 
            return _isImageValid;
        }
        set
        {
            _isImageValid = value;
            this.RaisePropertyChanged(() => this.IsImageValid);
        }
    }
}
ViewModel
公共类MetadataViewModel:NotificationObject,IMetadataViewModel
{
#区域::属性::
私有事件聚合器;
专用iImageResizer服务imageResizer;
私有字符串头信息;
公共字符串头信息
{
得到
{
返回headerInfo;
}
设置
{
if(this.headerInfo!=值)
{
this.headerInfo=值;
this.RaisePropertyChanged(()=>this.HeaderInfo);
}
}
}
公共ICommand SaveCommand
{
得到;
私人设置;
}
公共ICommand CloseCommand
{
得到;
私人设置;
}
公共ICommand delete命令
{
得到;
私人设置;
}
公共ICommand提交命令
{
得到;
私人设置;
}
公共ICommand未提交命令
{
得到;
私人设置;
}
公共ICommand LocationSearchCommand
{
得到;
私人设置;
}
公共ICommand SubjectSearchCommand
{
得到;
私人设置;
}
公用ICommand RemovelociationCommand
{
得到;
私人设置;
}
public ICommand removesubject命令
{
得到;
私人设置;
}
私有故事项selectedStory;
公共故事项SelectedStory
{
得到
{
返回此。selectedStory;
}
设置
{
if(this.selectedStory!=值)
{
this.selectedStory=值;
this.raiseProperty已更改(()=>this.SelectedStory);
//提出依赖项
this.RaisePropertyChanged(()=>this.CanSave);
this.raiseProperty已更改(()=>this.CanUnSubmit);
this.RaisePropertyChanged(()=>this.CanDelete);
}
}
}
公共列表程序列表
{ 
得到;
私人设置;
}
公开列表GenreList
{ 
得到;
私人设置;
}
公共列表版权列表
{ 
得到;
私人设置;
}
公共图书馆可以保存
{
得到
{
bool canSave=false;
if(this.SelectedStory.IsLockAvailable)
{
如果(!this.SelectedStory.Submitted)
{
canSave=true;
}
}
还可以保存;
}
}
公共场所烛台
{
得到
{
布尔坎德莱特=假;
if(this.SelectedStory.IsLockAvailable)
{
如果(!this.SelectedStory.Submitted)
{
坎德莱特=真;
}
}
返回烛台;
}
}
公共图书馆无法提交
{
得到
{
bool canUnSubmit=false;
if(this.SelectedStory.IsLockAvailable)
{
if(this.SelectedStory.Submitted)
{
canUnSubmit=true;
}
}
返回不提交;
}
}
#端区
#区域::构造函数::
[导入构造函数]
公共元数据视图模型(
IMetadataController元数据控制器,
服务网关,
INavigationService navigator,
iImageResizer服务imageResizer,
IEventAggregator事件聚合器
)
{
this.eventAggregator=eventAggregator;
this.imageResizer=imageResizer;
//填充下拉列表
this.ProgramList=gateway.GetPrograms(true);
this.GenreList=gateway.GetGenres();
this.CopyrightList=gateway.GetCopyrights();
//添加虚拟值,以便用户可以取消选择
this.ProgramList.Add(new Program());
this.GenreList.Add(新流派());
this.CopyrightList.Add(新版权());
//命令
this.SaveCommand=metadataController.SaveCommand;
this.CloseCommand=metadataController.CloseCommand;
this.DeleteCommand=metadataController.DeleteCommand;
this.SubmitCommand=metadataController.SubmitCommand;
this.UnSubmitCommand=metadataController.UnSubmitCommand;
this.LocationSearch命令=新的DelegateCommand(this.LocationSearch);
this.SubjectSearchCommand=新的DelegateCommand(this.SubjectSearch);
this.RemoveLocationCommand=新的DelegateCommand(this.RemoveLocation);
this.RemoveSubjectCommand=新的DelegateCommand(this.RemoveSubject);
//事件
this.eventAggregator.GetEvent().Subscribe(OnStorySelected,ThreadOption.UIThread);
this.eventAggregator.GetEvent().Subscribe(OnAddLocation,ThreadOption.UIThread);
this.eventAggregator.GetEvent().Subscribe(OnAddSubject,ThreadOption.UIThread);
this.eventAggregator.GetEvent().Subscribe(OnCommandCompleted,ThreadOption.UIThread);
this.eventAggregator.GetEvent().Subscribe(OnImageResizeCompleted,ThreadOption.UIThread);
这是初始化();
}
#端区
已选择StorySelected上的私有无效(StoryItem selectedStory)
{
if(this.selectedStory!=null)
  ViewModel

 public class MetadataViewModel : NotificationObject, IMetadataViewModel
{
    #region :: Properties ::

    private IEventAggregator eventAggregator;
    private IImageResizerService imageResizer;

    private string headerInfo;
    public string HeaderInfo
    {
        get
        {
            return headerInfo;
        }
        set
        {
            if (this.headerInfo != value)
            {
                this.headerInfo = value;
                this.RaisePropertyChanged(() => this.HeaderInfo);
            }
        }
    }

    public ICommand SaveCommand
    {
        get;
        private set;
    }

    public ICommand CloseCommand
    {
        get;
        private set;
    }

    public ICommand DeleteCommand
    {
        get;
        private set;
    }

    public ICommand SubmitCommand
    {
        get;
        private set;
    }

    public ICommand UnSubmitCommand
    {
        get;
        private set;
    }

    public ICommand LocationSearchCommand
    {
        get;
        private set;
    }

    public ICommand SubjectSearchCommand
    {
        get;
        private set;
    }

    public ICommand RemoveLocationCommand
    {
        get;
        private set;
    }

    public ICommand RemoveSubjectCommand
    {
        get;
        private set;
    }

    private StoryItem selectedStory;
    public StoryItem SelectedStory
    {
        get
        {
            return this.selectedStory;
        }
        set
        {
            if (this.selectedStory != value)
            {
                this.selectedStory = value;
                this.RaisePropertyChanged(() => this.SelectedStory);

                // raise dependencies
                this.RaisePropertyChanged(() => this.CanSave);
                this.RaisePropertyChanged(() => this.CanUnSubmit);
                this.RaisePropertyChanged(() => this.CanDelete);

            }
        }
    }


    public List<Program> ProgramList 
    { 
        get; 
        private set; 
    }

    public List<Genre> GenreList 
    { 
        get; 
        private set; 
    }

    public List<Copyright> CopyrightList 
    { 
        get; 
        private set; 
    }

    public bool CanSave
    {
        get
        {
            bool canSave = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (!this.SelectedStory.Submitted)
                {
                    canSave = true;
                }
            }

            return canSave;
        }
    }

    public bool CanDelete
    {
        get
        {
            bool canDelete = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (!this.SelectedStory.Submitted)
                {
                    canDelete = true;
                }
            }

            return canDelete;
        }
    }



    public bool CanUnSubmit
    {
        get
        {
            bool canUnSubmit = false;

            if (this.SelectedStory.IsLockAvailable)
            {
                if (this.SelectedStory.Submitted)
                {
                    canUnSubmit = true;
                }
            }

            return canUnSubmit;
        }
    }

    #endregion

    #region :: Contructor ::

    [ImportingConstructor]
    public MetadataViewModel(
            IMetadataController metadataController, 
            IGatewayService gateway, 
            INavigationService navigator,
            IImageResizerService imageResizer,
            IEventAggregator eventAggregator
        )
    {
        this.eventAggregator = eventAggregator;
        this.imageResizer = imageResizer;

        // populate drop-down lists
        this.ProgramList = gateway.GetPrograms(true);
        this.GenreList = gateway.GetGenres();
        this.CopyrightList = gateway.GetCopyrights();

        // add dummy values so the user can de-select
        this.ProgramList.Add(new Program());
        this.GenreList.Add(new Genre());
        this.CopyrightList.Add(new Copyright());

        // commands
        this.SaveCommand = metadataController.SaveCommand;
        this.CloseCommand = metadataController.CloseCommand;
        this.DeleteCommand = metadataController.DeleteCommand;
        this.SubmitCommand = metadataController.SubmitCommand;
        this.UnSubmitCommand = metadataController.UnSubmitCommand;



        this.LocationSearchCommand = new DelegateCommand<string>(this.LocationSearch);
        this.SubjectSearchCommand = new DelegateCommand<string>(this.SubjectSearch);
        this.RemoveLocationCommand = new DelegateCommand<Topic>(this.RemoveLocation);
        this.RemoveSubjectCommand = new DelegateCommand<Topic>(this.RemoveSubject);

        // events
        this.eventAggregator.GetEvent<StorySelectedEvent>().Subscribe(OnStorySelected, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<AddLocationEvent>().Subscribe(OnAddLocation, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<AddSubjectEvent>().Subscribe(OnAddSubject, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<CommandCompletedEvent>().Subscribe(OnCommandCompleted, ThreadOption.UIThread);
        this.eventAggregator.GetEvent<ImageResizeCompletedEvent>().Subscribe(OnImageResizeCompleted, ThreadOption.UIThread);

        this.Initialize();
    }

    #endregion

    private void OnStorySelected(StoryItem selectedStory)
    {
        if (this.selectedStory != null)
        {
            this.Initialize();

            // override the initialized values
            this.SelectedStory = selectedStory;
            this.SelectedStory.HaveChanged = false;
            this.HeaderInfo = "Edit";
        }
    }

    public void OnAddLocation(Topic topic)
    {
        if (topic != null)
        {
            if (!this.SelectedStory.Locations.Contains(topic))
            {
                this.SelectedStory.Locations.Add(topic);
                this.RaisePropertyChanged(() => this.SelectedStory.Locations);
            }
        }
    }

    public void OnAddSubject(Topic topic)
    {
        if (topic != null)
        {
            if (!this.SelectedStory.Subjects.Contains(topic))
            {
                this.SelectedStory.Subjects.Add(topic);
                this.RaisePropertyChanged(() => this.SelectedStory.Subjects);
            }
        }
    }

    private void OnCommandCompleted(string commandType)
    {
        if (commandType == CommandTypes.MetadataEntry)
        {
            this.Initialize();
        }
    }

    private void OnImageResizeCompleted(bool isSuccessful)
    {
        IsImageValid = false;
        if (isSuccessful)
        {

            this.SelectedStory.KeyframeImages = true;
            IsImageValid = true;
        }
        else
        {
            this.SelectedStory.KeyframeImages = false;
            IsImageValid=false;
        }
    }

    private void Initialize()
    {
        this.SelectedStory = new StoryItem();
        this.HeaderInfo = "Create";
    }

    private void LocationSearch(object topicType)
    {
        this.eventAggregator.GetEvent<LocationSearchEvent>().Publish(null);
    }

    private void SubjectSearch(object topicType)
    {
        this.eventAggregator.GetEvent<SubjectSearchEvent>().Publish(null);
    }

    private void RemoveLocation(Topic selected)
    {
        if (selected != null)
        {
            // remove the primary too
            if (this.SelectedStory.PrimaryLocation != null)
            {
                if (string.Equals(this.SelectedStory.PrimaryLocation.FullName, selected.FullName, StringComparison.InvariantCultureIgnoreCase))
                {
                    this.SelectedStory.PrimaryLocation = new Topic();
                }
            }

            bool isSuccessful = this.SelectedStory.Locations.Remove(selected);
            if (isSuccessful)
            {
                this.RaisePropertyChanged(() => this.SelectedStory.Locations);
            }
        }
    }

    private void RemoveSubject(Topic selected)
    {
        if (selected != null)
        {
            // remove the primary too
            if (this.SelectedStory.PrimarySubject != null)
            {
                if (string.Equals(this.SelectedStory.PrimarySubject.FullName, selected.FullName, StringComparison.InvariantCultureIgnoreCase))
                {
                    this.SelectedStory.PrimarySubject = new Topic();
                }
            }

            bool isSuccessful = this.SelectedStory.Subjects.Remove(selected);
            if (isSuccessful)
            {
                this.RaisePropertyChanged(() => this.SelectedStory.Subjects);
            }
        }
    }
}

        private booly _isImageValid;

        public bool IsImageValid
        {
        get
        { 
            return _isImageValid;
        }
        set
        {
            _isImageValid = value;
            this.RaisePropertyChanged(() => this.IsImageValid);
        }
    }
}
<UserControl.Resources>
  <BooleanToVisibilityConverter
         x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
Then use it in one or more bindings like this:

<Label Visibility="{Binding IsImageValid, 
       Converter={StaticResource BooleanToVisibilityConverter}}" 
   ......... />
xmlns:VM="clr-namespace:<ProjectName>.ViewModels" //this place throws exception,what is <ProjectName> ?
<UserControl.DataContext>     //where to add this part ?  
    <VM:MyViewModel>
</UserControl.DataContext>
Visibility="{Binding IsImageValid}"   //this is done
namespace MyApp.ViewModels           //this i have to do it at xaml.cs file  or suppose to be in viewmodel ?
{
    public class MyViewModel : INotifyPropertyChanged
    {...
     ...
    }
}
private System.Windows.Visibility _isImageValid; //add this code in my viewmodel

public System.Windows.Visibility IsImageValid
{
    get
    { 
        return _isImageValid;
    }
    set
    {
        _isImageValid = value;
        this.RaisePropertyChanged(() => this.IsImageValid);
    }
}