WPF桌面端开发3-数据绑定

2020-05-09 14:57:16 浏览数 (1)

数据绑定

定义基类

代码语言:javascript复制
using System.ComponentModel;

namespace ZJClassTool.Utils
{
    public class MyNotifyModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

定义数据源的类

代码语言:javascript复制
public class ToolbarModel : MyNotifyModel
{
    public ObservableCollection<ToolbarMenu> menuList { get; set; }
    bool _IsRight = true;
    public bool IsRight
    {
        get { return _IsRight; }
        set { _IsRight = value; OnPropertyChanged("IsRight"); }
    }
    public ToolbarModel()
    {
        menuList = new ObservableCollection<ToolbarMenu>();
    }
}

public class ToolbarMenu : MyNotifyModel
{
    string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; OnPropertyChanged("Name"); }
    }

    public string Pic { get; set; }
}

上面例子中我们可以看到,

如果我们要在数据改变时通知页面改变的属性都要在Set方法中调用OnPropertyChanged

而列表不再用List,而是使用ObservableCollection

代码中也要进行数据源的设置

代码语言:javascript复制
pageData.IsRight = true;
pageData.menuList.Add(new ToolbarMenu()
    {
        Name = "开始直播",
        Pic = "Images/ToolBar/toobar_12_1.png"
    });
DataContext = pageData;

上面设置整个页面的数据,当然也可以设置某个组件的数据源

代码语言:javascript复制
this.toolbar_list.DataContext = mydata;

页面中绑定值

代码语言:javascript复制
<Window.Resources>
    <DataTemplate x:Key="ToolbarMenu">
        <Button x:Name="toolbar_item"  Background="Transparent" BorderThickness="0" Cursor="Hand" Height="60" Click="toolbar_item_Click">
            <Button.Content>
                <StackPanel Width="Auto" Background="Transparent">
                    <Image HorizontalAlignment="Center" Width="44" Source="{Binding Pic}"/>
                    <TextBlock HorizontalAlignment="Center" Text="{Binding Name}" Foreground="#3C525B"/>
                </StackPanel>
            </Button.Content>
        </Button>
    </DataTemplate>
</Window.Resources>
<ItemsControl 
    x:Name="toolbar_list"
    ItemsSource="{Binding menuList}"
    ItemTemplate="{StaticResource ToolbarMenu}"
    ScrollViewer.VerticalScrollBarVisibility="Disabled"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled"
    Grid.Row="1" Background="#f3f3f3" BorderThickness="0">
</ItemsControl>

双向绑定

代码语言:javascript复制
<TextBox Grid.Row="0" Text="{Binding Title,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>
<TextBlock Grid.Row="0" Text="{Binding Path=Title}"/>

关键属性 UpdateSourceTrigger=PropertyChanged,Mode=TwoWay

0 人点赞