实现内容
- 在主页调用控件时,可通过修改用户控件的value属性更改用户控件显示的值
- 用户控件的value属性可以被Binding动态值
注意
- 调用 用户控件时,需要在Binding内添加Mode=TwoWay属性
- 用户控件需要在Binding内添加RelativeSource={RelativeSource AncestorType=UserControl}属性
代码
用户控件代码
用户控件前台MyUserControl.xaml
<UserControl x:Class="WpfApp1.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBox x:Name="txtValue" Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</Grid>
</UserControl>
用户控件后台MyUserControl.xaml.cs
添加一个名为"Value"的依赖属性,这将允许我们Binding用户控件的值。
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1
{
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(MyUserControl), new PropertyMetadata(null));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public MyUserControl()
{
InitializeComponent();
}
}
}
主页代码
主页前台MyUserControl.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx="/"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:MyUserControl Value="{Binding MyValue, Mode=TwoWay}"/>
</Grid>
</Window>
主页后台MainWindow.xaml.cs
添加一个名为"MyValue"的属性。这个属性将用于和"MyUserControl"中的"Value"属性进行双向绑定。
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string myValue;
public string MyValue
{
get { return myValue; }
set
{
myValue = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
//这里的函数类型和函数参数没做过验证,要注意下
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
现在你可以运行项目,用户控件将会在主页中显示一个带有TextBox的窗口。你可以通过修改"MyValue"属性来改变用户控件中TextBox的值,并且用户控件的值也可以被绑定到其他动态值。
现在我们的用户控件已经完成了。在主页中使用该用户控件时,你可以通过修改value属性来改变TextBox的值,并且value属性也可以绑定到其他动态值。