WPF怎么把一个控件的值绑定到一个变量啊?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF怎么把一个控件的值绑定到一个变量啊?相关的知识,希望对你有一定的参考价值。

参考技术A public class Person : INotifyPropertyChanged

private string name;
private int age;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public Person()


public Person(string value)

this.name = value;

public string PersonName

get return name;
set

name = value;
OnPropertyChanged("PersonName");


public int Age

get return age;
set

age = value;
OnPropertyChanged("Age");


// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)

if (PropertyChanged != null)

PropertyChanged(this, new PropertyChangedEventArgs(name));



//=========================================
private void SetBinding()

Person person = new Person();
person.Age = 45;
person.PersonName = "personname";
this.DataContext = person;

//==========================================
<Window x:Class="BindingSingleObject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingSingleObject"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:Person x:Key="person" PersonName="Name1" Age="40"/>
</Window.Resources>
<StackPanel>
<TextBox Text="Binding Source=StaticResource person, Path=Age"/>
<TextBox Text="Binding Path=Age, UpdateSourceTrigger=PropertyChanged"/>
<TextBox Text="Binding Path=Age,Mode=OneWay"/>
</StackPanel>
</Window>
参考技术B 基本的数据绑定即可 参考技术C 用双向绑定 Mode=twoway 参考技术D 就绑呗

在wpf中怎么绑定comboBox的值

前台:
<ComboBox Name="combobox" Width="120" Height="30"/>
后台:
public test5()

InitializeComponent();

Dictionary<int, string> mydic = new Dictionary<int, string>()

1,"a",
2,"b",
3,"c"
;
combobox.ItemsSource = mydic;
combobox.SelectedValuePath = "Key";
combobox.DisplayMemberPath = "Value";

ItemsSource 指定comboBox的数据源,可以是字典,list等任何形式的数据集合
SelectedValuePath 表示每个item的的实际值,DisplayMemberPath 表示每个item的显示值追问

很不错,我恍然大悟,很实用。我需要的就是绑定几个值,而不是从数据库查找,那combobox能不能改变他的原始样式啊!

追答

当然可以,所有UI控件都可以在style里指定样式。网上资源有很多的。你可以打关键词“wpf 样式模板”查询相关知识

参考技术A 改变样式有数据模版和控件模版

以上是关于WPF怎么把一个控件的值绑定到一个变量啊?的主要内容,如果未能解决你的问题,请参考以下文章

我可以从后面的 C# 代码更新 WPF 绑定的值吗?

WPF——ComboBox控件怎么绑定数据

WPF inputbox的问题

WPF 如何动态绑定static成员变量 并实现INOTIFYPROPERTYCHANGED方法

wpf checkbox 如何绑定变量

急等,在wpf中怎么才能把image控件的source属性绑定到listview中的选中项