我想創建一個UserControl,它本質上是帶有TextBox的Label。現在我想能夠將TextBox.Text
綁定到不同的值。如何正確設置用於綁定的WPF UserControl
爲此,我在我的UserControl中創建了一個DependencyProperty,現在我試圖將某些東西綁定到新創建的DependencyProperty,但是文本似乎沒有更新。
我UserControl1.xaml看起來是這樣的:
<UserControl x:Class="WpfApplication1.UserControl1"
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="48" d:DesignWidth="200">
<Grid>
<WrapPanel Height="48" HorizontalAlignment="Left" Name="wrapPanel1" VerticalAlignment="Top" Width="200">
<Label Content="Label" Height="48" Name="label1" Width="100" />
<TextBox Height="48" Name="textBox1" Width="100" />
</WrapPanel>
</Grid>
而且我UserControl1.xaml.cs看起來是這樣的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
private string value;
public string Value
{
get { return value; }
set
{
this.value = value;
textBox1.Text = value;
Trace.TraceInformation("value set in UserControl1");
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(UserControl1));
public UserControl1()
{
InitializeComponent();
}
}
}
我使用這樣的用戶控件:
<my:UserControl1 x:Name="userControl11" Value="{Binding Path=Name}" />
與DataContext
設置爲具有Name屬性並實現此屬性的INotifyPropertyChanged的對象。
我試過了,這讓我的用戶控件得到更新,但現在我似乎有一個不同的錯誤:每當我更改'userControl11.TextBox1.Text'它不會更新,當我的綁定數據再次更改。我嘗試在TextBox中放入'Text =「{Binding Path = Value,ElementName = root,Mode = TwoWay}」',但這並不幫助它。 – FlyingFoX
這很棘手。默認情況下,您的自定義依賴屬性是OneWay綁定,如果您在使用時未指定BindingMode。您有兩種選擇,一種是使用時指定Mode = TwoWay,另一種是覆蓋FrameworkPropertyMetadata以指定默認綁定模式爲TwoWay。 –