I use the 'UserControl' to implement a custom control. The process of data binding encountered a problem.
The UserControl contains a TextBox.
Code: Select all
<UserControl
x:Class="Client.PercentTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="root123" x:FieldModifier="private"
xmlns:local="clr-namespace:Client">
<TextBox DataContext="{Binding ElementName=root123}" Width="{Binding Width}" Height="{Binding Height}"
Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</UserControl>
And,define a variable in it.
Code: Select all
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value", typeof(double), typeof(PercentTextBox), new PropertyMetadata(0.0));
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
mainPage.xaml
Code: Select all
<Page
x:Class="Client.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Client"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:client="clr-namespace:Client"
mc:Ignorable="d">
<Canvas Width="500" Height="500" x:Name="g">
<client:PercentTextBox Canvas.Left="20" Canvas.Top="100" Width="100" Height="50" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0 100 0 0"
Value="{Binding Path=Name, Mode=TwoWay}"></client:PercentTextBox>
<Button Canvas.Left="20" Canvas.Top="150" Click="Button_Click">btn1</Button>
<Button Canvas.Left="90" Canvas.Top="150" Click="Button_Click_1">btn2</Button>
</Canvas>
</Page>
mainPage.cs
Code: Select all
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace Client
{
public partial class MainPage : Page
{
Company mCompany = new Company();
public MainPage()
{
this.InitializeComponent();
// Enter construction logic here...
mCompany = new Company { Name = 1.2 };
this.g.DataContext = mCompany;
}
public class Company : INotifyPropertyChanged
{
private double name;
public event PropertyChangedEventHandler PropertyChanged;
public double Name
{
get { return name; }
set
{
name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
mCompany.Name = 3.0;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show((this.g.DataContext as Company).Name.ToString());
}
}
}
Data binding can not work well. In particular,Textbox can not represent data,and input data into textbox,the DataContext does not get the correct value.
How to solve this problem, how to use UserControl to achieve custom control data binding?
Thanks!