固定最简步骤,包括
XAML:
题头里引入命名空间
标题下面引入类
combobox绑定资源属性和选择属性,block则绑定和combobox一样的选择属性
C#:
通知的类,及对应固定的任务
引入字段
引入属性
其中资源是只读的
选择属性是单触发,必须要加nameof
属性
block=>指向box的属性
这是最简形式
<Window x:Class="绑定类型2_combobox.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:MainWindow_ViewModel"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.DataContext><local:MainWindowViewModel/></Window.DataContext><Grid><ComboBox HorizontalAlignment="Left" Margin="378,142,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding Item_source}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/><TextBlock HorizontalAlignment="Left" Margin="378,187,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding SelectedItem}"/></Grid>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Web;namespace MainWindow_ViewModel
{class MainWindowViewModel:INotifyPropertyChanged{private string[] item_source = { "6dB/oct", "12dB/oct", "18dB/oct", "24dB/oct", "30dB/oct", "36dB/oct", "42dB/oct", "48dB/oct" };private string selectedItem;public string[] Item_source{get { return item_source; }}public string SelectedItem{get { return selectedItem; }set{selectedItem = value;OnPropertyChanged(nameof(SelectedItem));}}//固定public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}}
}
也可以block绑定单独一个属性,像之前那样
public string SelectedItem{get { return selectedItem; }set{selectedItem = value;OnPropertyChanged(nameof(SelectedItem));OnPropertyChanged(nameof(SelectedItemDisplay));}}public string SelectedItemDisplay => SelectedItem;
<ComboBox HorizontalAlignment="Left" Margin="378,142,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding Item_source}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/><TextBlock HorizontalAlignment="Left" Margin="378,187,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding SelectedItemDisplay}"/>