簡體   English   中英

如何從ViewModel(WPF)引用UI元素?

[英]How to reference an UI element from ViewModel (WPF)?

這對你們來說可能很簡單,但只是從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>

標簽

<Label Name="IsImageValid"  Content="Image Created" Margin="0,7,-1,0" Style="{StaticResource LabelField}"
                    Grid.ColumnSpan="2" Grid.Row="15" Width="90" Height="28" Grid.RowSpan="2"
                    Grid.Column="1" IsEnabled="True" 
                    Visibility="{Binding IsImageValid,Converter={StaticResource BooleanToVisibilityConverter}}" />

我試圖在我的視圖模型中調用此標簽,但不確定如何。

我在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中具有一個布爾屬性,例如“ IsImageValid” ...然后在XAML中,使用BooleanToVisibilityConverter http://msdn.microsoft.com/zh-CN將標簽的Visibility屬性綁定到該屬性。 我們/library/system.windows.controls.booleantovisibilityconverter.aspx

<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}}" 
   ......... />

請先閱讀這篇文章。

如果要在標簽中顯示一些文本,則必須執行以下步驟:

  • 屬性添加到您的Viewmodel
  • 在您的Viewmodel中實現INotifyPropertyChanged並在屬性更改時引發事件
  • 在您的視圖中將DataContext設置為您的Viewmodel實例
  • 在xaml中創建到您的媒體資源的綁定

就這樣 ;)

您不必從ViewModel中查看View,這是MVVM模式背后的基本原理。 View了解VM,而VM不了解View。 相反,您可以按照@ JeffN825的建議進行操作,至少我也建議這樣做。

將以下內容添加到您的用戶控件屬性中:

xmlns:VM="clr-namespace:<ProjectName>.ViewModels" //this place throws exception,what is <ProjectName> ?

若要將DataContext分配給用戶控件,請使用以下代碼(如果尚未分配DataContext):

<UserControl.DataContext>     //where to add this part ?  
    <VM:MyViewModel>
</UserControl.DataContext>

通過以下方式綁定標簽的可見性:

Visibility="{Binding IsImageValid}"   //this is done

從中繼承VM的ViewModel或ViewModelBase應該實現INotifyPropertyChanged接口:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM