我覺得我可能在這里遺漏了一些東西,或者它不可行(我很難相信)。
我有一個使用 MVVM 架構的 UserControl。
UserControl 看起來像這樣。
public partial class UserControl1 : UserControl
{
private string _labelContents;
public UserControl1()
{
InitializeComponent();
DataContext = new UserControl1_VM();
}
}
虛擬機看起來像這樣。
公共類UserControl1_VM:INotifyPropertyChanged {私有字串_labelContents =“從VM設定”;
public string LabelContent
{
get => _labelContents;
set { _labelContents = value; OnPropertyChanged("LabelContent"); }
}
public event PropertyChangedEventHandler? PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我希望能夠放入 MainView 或類似的:
<mv:UserControl1 LabelContent="My Text"></mv:UserControl1>
但是 VS 宣告它“無法決議符號 LabelContent”。這是可以理解的,因為它在視圖模型中。如果不將該屬性放入 UserControl 后面的代碼中,并通過它傳遞值似乎是不可能的。我可能只是在尋找錯誤的東西。
這是一個非常基本的例子,但我認為 LabelContent 需要是一個依賴屬性,因為它本身即最終系結到它。
<mv:UserControl1 LabelContent="{Binding LabelText}"></mv:UserControl1>
對此有任何幫助都會很棒,因為它讓我撓頭,讓我禿頂!!
只是為了讓您知道它是否不是依賴屬性,但它看起來很笨拙。
干杯
詹姆士
uj5u.com熱心網友回復:
您不需要 UserControl 的任何視圖模型,只需要一個依賴屬性:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string LabelContent
{
get { return (string)GetValue(LabelContentProperty); }
set { SetValue(LabelContentProperty, value); }
}
public static readonly DependencyProperty LabelContentProperty = DependencyProperty.Register
(
nameof(LabelContent),
typeof(string),
typeof(UserControl1),
new PropertyMetadata(String.Empty)
);
}
然后將其放在視圖中并分配或系結屬性:
<mv:UserControl1 Name="uc1" LabelContent="My Text"/>
<mv:UserControl1 Name="uc2" LabelContent="{Binding Path=LabelContent, ElementName=uc1}"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489985.html
上一篇:WPF-Listview資料系結到Web套接字資料太慢
下一篇:路徑與段不重合
