我有視圖模型如何將對象傳遞給ViewModel在MVVM中構建時?
public class VM: DependencyObject, INotifyPropertyChanged
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(VM), new PropertyMetadata(""));
public int Length
{
get
{
return Text != null ? Text.Length : 0;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
,並查看它
<UserControl.DataContext>
<local:VM Text="{Binding ControlText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
</UserControl.DataContext>
<StackPanel>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="{Binding Length}"/>
</StackPanel>
是的,觀點也落後
public string ControlText
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("ControlText", typeof(string), typeof(Writer), new PropertyMetadata(""));
代碼依賴屬性我上輸出了錯誤日誌
System.Windows.Data錯誤:4:無法找到bindin的源代碼g引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.UserControl',AncestorLevel ='1''。 BindingExpression:路徑= ControlText;的DataItem = NULL;目標元素是'VM'(HashCode = 21019086);目標屬性是'文本'(類型'字符串')
當這個技術工作時,我將有工具來構建我的viewmodel。 也許任何人都知道如何將此視圖屬性綁定到viewmodel屬性或知道技術如何正確執行:)
我知道, 和你顯示我最後feaute是我在作家(UserCntrol)中使依賴屬性的主要原因。 但我想做點這樣的事: 我有字符串屬性 string s {get;設置;} 我創建Writer(UserControl),並通過綁定創建的用戶控件傳遞此字符串。 現在我想要一個UserCOntrol將屬性s傳遞給Viewmodel。 所以我想在Writer.xaml中做 這就是構建Viewmodel通過視圖的要點。 property is s draging throught view to viewmodel –
Jan3Sobieski