English 中文(简体)
如何改变我对XAML有约束力的代码后面的代码
原标题:How to change my code-behind binding to XAML binding

我新到 C# 和 WPF 。 我写了一个简单的程序。 我有一个名为 < code> Counter 的类, 显示从 0 开始的只读属性 < code> < count , 以及一个仅加注一个数的公共方法 < code> incrimination 。 < code> Counter 执行 < code> Property Changed 。

我有一个窗口类( 代码在下面) 。 我将一个 < code> counter 对象实例传递给构建者, 并执行一个绑定。 窗口有一个按钮和一个标签。 标签被绑在 code > count 属性上, 按钮调用 < code > Incrowment

这一切都有效。

然而,我所看到的多数例子都围绕网络, MSDN大多涉及XAML中的约束性定义。 我怎样才能修改我的例子来将约束性操作从代码后面移到标记上? VS 2010 属性窗口中的约束性属性似乎不知道如何做我想做的事。 也许这不可能吗?

还有一个问题: 我不认为这个例子适合MVVM... 我的反向类单独存在, 除了通过它的属性之外, 没有与任何地方的视图相连。 但是, 反视类持有一个引用它的位置 。 这是这个引用的适当位置吗? 我虽然也认为我应该创建窗口, 然后设定一个属性( 如 < code> CounterObject ), 而不是通过构建器。

public partial class CounterWindow : Window {
    Counter ctr;

    public CounterWindow(Counter ctr) {
        InitializeComponent();

        this.ctr = ctr;
        Binding b = new Binding("Count");
        b.Source = ctr;
        CounterLabel.SetBinding(Label.ContentProperty, b);
    }

    private void IncrementButton_Click(object sender, RoutedEventArgs e) {
        ctr.Increment();
    }
}
最佳回答

像这样的事情:

public CounterWindow(Counter ctr) 
{
    InitializeComponent();
    DataContext = ctr;
}

标记 :

<Label Content="{Binding Count}" />  

UPD. There s two common approaches in MVVM: view-first and model-first.
View first means that you initially create the view, and then view creates view model, which it is bound to.
Model-first means that first you create the view model, then view model creates its view and passes itself (via constructor or via DataContext property setter) as data context of the view.

希望这能帮到你

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签