본질적으로 TextBox가있는 Label 인 UserControl을 만들고 싶습니다. 이제 TextBox.Text
을 다른 값으로 바인딩 할 수 있기를 바래요.바인딩을위한 WPF UserControl을 올바르게 설정하는 방법
이 들어 나는 내 UserControl에 DependencyProperty를 만들었습니다. 그리고 새로 생성 된 DependencyProperty에 뭔가를 바인딩하려하지만 텍스트가 업데이트되지 않는 것 같습니다.
<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은 다음과 같습니다 :
내 UserControl1.xaml은 다음과 같습니다 나는이 같은 UserControl을 사용하고
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를 구현하는 개체로 설정됩니다.
필자는 그것으로 인해 내 userControl이 업데이트되었지만 이제는 다른 버그가있는 것 같습니다. 'userControl11.TextBox1.Text'를 변경할 때마다 바운드 데이터가 다시 변경 될 때 업데이트되지 않습니다. TextBox에'Text = "{Binding Path = Value, ElementName = root, Mode = TwoWay}"'를 넣으려고했지만 그게 도움이되지 않습니다. – FlyingFoX
그건 까다 롭습니다. BindingMode를 사용할 때 지정하지 않으면 기본적으로 사용자 지정 종속성 속성은 OneWay 바인딩입니다. 두 가지 선택 사항이 있습니다. 하나는 Mode = TwoWay로 지정하고, 두 번째는 FrameworkPropertyMetadata를 덮어 쓰면 기본 바인딩 모드가 TwoWay로 지정됩니다. –