一、INotifyPropertyChanged(View-ViewModel属性值改变通知属性)
1、封装INotifyPropertyChanged接口
using System.ComponentModel;
public class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void DoNotify([CallerMemberName] string propName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
2、使用NotifyBase.cs(存放于Common路径下)
A、引用Common命名空间
B、使用方法
例:
public class WindElementViewData :NotifyBase
{//快捷键 propfull
private string _viewTime = "未查看";
public string ViewTime { get { return _viewTime; } set { _viewTime = value; DoNotify("ViewTime"); } }
}
二、ICommand(View Command绑定接口 在ViewModel中进行具体实现)
1、封装ICommand接口
using System.Windows.Input;
public class CommandBase : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return DoCanExcute?.Invoke(parameter) == true ? true : false;
}
public void Execute(object parameter)
{
DoExcute?.Invoke(parameter);
}
public Action<object> DoExcute { get; set; }
public Func<object, bool> DoCanExcute { get; set; }
}
2、使用CommandBase .cs(存放于Common路径下)
A、引用Common命名空间
B、使用方法
例:
public TestDemo()
{
TestCommand = new CommandBase()
{
DoCanExcute = new Func<object, bool>(o => { return true; }),
DoExcute = new Action<object>(DoTestCommand)
};
}
三、IValueConverter(属性值转换)
1、cs中使用方法
using System.Windows.Data
public class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ListViewItem item = (ListViewItem)value;
ListView listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
// Get the index of a ListViewItem
int index = listView.ItemContainerGenerator.IndexFromContainer(item);
if (index % 2 == 0)
{
return Brushes.LightSteelBlue;
}
else
{
return Brushes.White;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}