WPF MVVM 模式下後臺事件在前臺的呼叫和繫結
方法一、事件觸發器(EventSetter)比較通用的方法不只限於MVVM模式
1、在前臺樣式中定義事件觸發器並指定事件型別和事件名
1是事件型別:這取決於樣式定義的是什麼控制元件,不同的控制元件有不同的事件
2是要在後臺編寫的事件名稱
2、前臺定義好後在後臺生成同名的方法,在其中編寫所有程式碼就行了。
方法二:利用依賴屬性的回撥驗證方法
下面這段程式碼採用用的是指定依賴屬性時,在初始化中指定回撥函式,這樣做雖然方便但是必須是靜態方法,不便於在前臺繫結
public string InputValue { get { return (string)GetValue(InputValueProperty); } set { SetValue(InputValueProperty, value); } } public static readonly DependencyProperty InputValueProperty = DependencyProperty.Register("InputValue", typeof(string), typeof(A_Write_1), new UIPropertyMetadata(new PropertyChangedCallback(ValueChanged))); public static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { A_Write_1 my = d as A_Write_1; my.TransferVal(my.ValueConvert(e.NewValue.ToString())); }
另外一種做法是
1、首先在後臺定義一個依賴屬性
public bool AnimationTypeNO
{
get { return (bool)GetValue(AnimationTypeNOProperty); }
set { SetValue(AnimationTypeNOProperty, value); }
}
public static readonly DependencyProperty AnimationTypeNOProperty =
DependencyProperty.Register("AnimationTypeNO", typeof(bool), typeof(ParaSetView), new UIPropertyMetadata(false));
在建構函式中定義回撥函式
DependencyPropertyDescriptor aaaaa = DependencyPropertyDescriptor.FromProperty(RadioButton.IsCheckedProperty, typeof(RadioButton));
aaaaa.AddValueChanged(aaaa, tbxEditMe_TextChanged);
typeof(RadioButton):是回撥函式要繫結的前臺控制元件型別
RadioButton.IsCheckedProperty;是回撥函式要繫結的前臺控制元件的屬性(必須是依賴屬性)
aaaa:是前臺要繫結的控制元件名
tbxEditMe_TextChanged:是前臺要繫結的方法名
定義方法
private void tbxEditMe_TextChanged(object sender, EventArgs e)
{
...................
}
最後在前臺新增對應控制元件並繫結依賴屬性就可以了
方法三、Command繫結MVVM方式
1、在ViewMode中定義Command類和方法體
//定義繼承類ICommand介面的類屬性 public RelayCommand<string> Init2Command { get; set; } //定義方法體 private void Init2(string ColumnsName) { // } //在建構函式中生成時間委託 public ParaSetViewModel() { Init2Command = new RelayCommand<string>(t => Init2(t)); }
2、在前臺控制元件中定義事件觸發器就可以
// 繫結到ListBox的點選事件 <ListBox x:Name="SubRoot" Background="{x:Null}" BorderBrush="{x:Null}" ItemsSource="{Binding ParaSet2PropertyList}" SelectedItem="{Binding ParaSet2Property}" ItemContainerStyle="{StaticResource Catalogue1}">
//事件觸發器 <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged" > <i:InvokeCommandAction Command="{Binding Init2Command}" CommandParameter="{Binding ParaSet2Property.GROUP}" /> </i:EventTrigger> </i:Interaction.Triggers> <ListBox.ItemTemplate> <DataTemplate > <StackPanel Width="120"> <TextBlock Text="{Binding GROUP}" Tag="{Binding NodeText10}" Foreground="White" FontSize="18" Padding="5,0" HorizontalAlignment="Stretch" VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>