テンプレート10とMVVMを使用してUWPアプリケーションを作成しています。私の要件は、独自のViewModelを持つだけでなく、独自の依存プロパティを持つUserControlを作成することです。独自のViewModelを持つUWP UserControlとテンプレート10を使用する依存関係プロパティ
私の要件:ボタンのクリックで
- コール親ViewModelにコマンド。
- バインドTexBlockテキストからユーザーコントロールのViewModel
私のユーザーコントロールは、次のようになります。
<vm:MyUserControl1 AddItem="{Binding MyCommand}" Component="{Binding}" RelativePanel.Below="abc" />
ユーザーコントロールのXAML:
:これは、コードの後ろにユーザーコントロールのコードが<StackPanel>
<TextBlock Text="{x:Bind Component.Text, Mode=OneWay}"/>
<Button x:Name="Button" Content="Click Me" Command="{x:Bind AddItem}">
</Button>
</StackPanel>
です
public sealed partial class MyUserControl1 : UserControl
{
public MyUserControl1()
{
this.InitializeComponent();
// mygrid.DataContext = this;
(this.Content as FrameworkElement).DataContext = this;
}
public static readonly DependencyProperty AddItemProperty =
DependencyProperty.Register(
"AddItem",
typeof(ICommand),
typeof(MyUserControl1), new PropertyMetadata(null));
public ICommand AddItem
{
get { return (ICommand)GetValue(AddItemProperty); }
set { SetValue(AddItemProperty, value); }
}
public static readonly DependencyProperty ComponentProperty = DependencyProperty.Register("Component",typeof(MyViewModel),typeof(MyUserControl1),new PropertyMetadata(null));
public MyViewModel Component
{
get { return (MyViewModel)GetValue(ComponentProperty); }
set { SetValue(ComponentProperty, value); }
}
}
ユーザーコントロールビューモデル:
public class MyViewModel:ViewModelBase
{
public MyViewModel()
{
}
public string Text => "ABC";
}
親ビューモデル:ここで間違って行くいただきまし
Unable to cast object of type 'WindowsApp2.ViewModels.SettingsPartViewModel' to type 'WindowsApp2.ViewModels.MyViewModel'.
:
public class SettingsPartViewModel : ViewModelBase
{
DelegateCommand _MyCommand;
public DelegateCommand MyCommand
=> _MyCommand ?? (_MyCommand = new DelegateCommand(async() =>
{
await Task.Run(() => {
///Some Code
});
}));
}
私は、コードを実行するたびに、私はエラーを次のですか?
はあなたのソリューションをありがとうございました。その期待通りに働いています。しかし、今私が直面している問題はUIに反映されないMyViewModelプロパティの値を変更する場合です。私はComponent = "{MyViewModelInstance、Mode = OneWayをバインドする"}をやってみましたが、まだ運がありません。助けてもらえますか –
あなたのコードを見ることなく、私はあなたを助けることができません。 'Mode = TwoWay'を試して、INotifyPropertyChangedインターフェースが正しく実装されているかどうかを確認してください。 – ViVi
完了。 ComponentプロパティモードをOneWayに設定すると、Text = "{x:Bind Component.Text、Mode = OneWay}"という問題が解決されます。すべてが魅力のように働いています。ありがとう! –