Tôi đã tạo một phiên bản đơn giản của mã của tôi trải nghiệm cùng một vấn đề. Vấn đề là tôi không chắc tại sao thuộc tính phụ thuộc trong điều khiển tùy chỉnh của tôi không cập nhật khi nó được thay đổi trong mô hình.Ràng buộc và ràng buộc thuộc tính phụ thuộc trong Kiểm soát tùy chỉnh
mẫu:
public class MainWindowModel : INotifyPropertyChanged
{
private bool isChecked;
public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); } }
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string prop)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<custom:CustomTextbox x:Name="TextboxName" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextChanged="CustomTextbox_TextChanged">
<custom:CustomTextbox.CustomTextboxItems>
<custom:CustomTextboxItem IsChecked="{Binding IsChecked}" />
</custom:CustomTextbox.CustomTextboxItems>
</custom:CustomTextbox>
<Button Content="Do It" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20" />
</Grid>
</Window>
Mã Đằng sau:
public partial class MainWindow : Window
{
MainWindowModel model;
public MainWindow()
{
InitializeComponent();
model = new MainWindowModel();
this.DataContext = model;
}
private void CustomTextbox_TextChanged(object sender, TextChangedEventArgs e)
{
model.IsChecked = true;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (TextboxName.CustomTextboxItems[0].IsChecked)
{
TextboxName.Text = "Property successfully changed";
}
}
}
Custom Control:
public class CustomTextbox : TextBox
{
public CustomTextbox()
{
CustomTextboxItems = new ObservableCollection<CustomTextboxItem>();
}
public ObservableCollection<CustomTextboxItem> CustomTextboxItems { get; set; }
}
public class CustomTextboxItem : FrameworkElement
{
public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(CustomTextboxItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
}
Như bạn có thể thấy trong điều khiển tùy chỉnh, tôi có một tập hợp các mục có chứa các đối tượng có thuộc tính phụ thuộc mà tôi muốn liên kết đến. Vì vậy, tôi tạo các đối tượng trong xaml và thiết lập ràng buộc, nhưng khi tôi cập nhật thuộc tính binded trong mô hình, nó không thay đổi nó trong điều khiển tùy chỉnh. Bất kỳ ý tưởng?
Cảm ơn bạn rất nhiều! – gamzu07
Liên kết đó đã chết, vui lòng cập nhật nó @kentboogaart –