1. 程式人生 > 其它 >WPF 非元素類繫結Binding之 DataContext 屬性

WPF 非元素類繫結Binding之 DataContext 屬性

這個是用的最多的一種方式:

XAML:

<Window.DataContext>
    <local:VMTempTest/>
</Window.DataContext>
<Grid>
    <StackPanel Orientation="Vertical" >

        <StackPanel Orientation="Horizontal" Margin="10 10 0 0">
            <TextBlock Text="名稱:" Width="100" ></TextBlock>
            <TextBox Text="{Binding Name}" Width="100" ></TextBox>
        </StackPanel>

        <StackPanel Orientation="Horizontal"  Margin="10 10 0 0">
            <TextBlock Text="性別:" Width="100" ></TextBlock>
            <TextBox Text="{Binding Sex}" Width="100" ></TextBox>
        </StackPanel>

    </StackPanel>
</Grid>

ViewModel:

public class VMTempTest : ViewModelBase
{
    private string _name = "小明";
    public string Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged(nameof(Name)); }
    }

    private string _sex = "男";
    public string  Sex
    {
        get { return _sex; }
        set { _sex = value; RaisePropertyChanged(nameof(Sex)); }
    }
}

繫結效果: