Khi tôi sử dụng UserControl tôi chuyển dữ liệu qua DependencyProperties. My UserControls không có ViewModels. UserControl chỉ xử lý dữ liệu được truyền theo một cách rất đặc biệt.
Nhưng nếu tôi có Chế độ xem có chứa một số Lượt xem phụ tôi đặt trước cho mỗi Mô hình con của riêng mình. Những mô hình này tôi sẽ ràng buộc thông qua một thuộc tính của ViewModel của MainView.
Một số ví dụ:
UserControl1, Mã đằng sau:
public partial class UserControl1 : UserControl
{
public MyClass MyProperty
{
get { return (MyClass)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(MyClass), typeof(UserControl1), new UIPropertyMetadata(null));
public UserControl1()
{
InitializeComponent();
}
}
public class MyClass
{
public int MyProperty { get; set; }
}
Và việc sử dụng trong giao diện, XAML:
<Window x:Class="Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Sandbox="clr-namespace:Sandbox">
<Grid>
<Sandbox:UserControl1 MyProperty="{Binding MyOtherPropertyOfTypeMyClassInMyViewModel, Mode=TwoWay}" />
</Grid>
Hope this helps
hi Tôi chưa bao giờ sử dụng DependencyProperties. Bạn có thể vui lòng cho tôi một liên kết hoặc giải thích ngắn gọn cách người dùng kiểm soát nên sử dụng Thuộc tính phụ thuộc hay không. Tôi có nên tạo một kiểu cho một userControl và sau đó liên kết nó với các thuộc tính khác nhau bên trong khung nhìn? – ganeshran
Tôi đã thêm một ví dụ đơn giản – WaltiD
Cảm ơn WaltiD tôi sẽ thử phương pháp này. Tôi cũng có thể liên kết nó với một kiểu người dùng đã định nghĩa không? – ganeshran