如何绑定wpf UserControl?

时间:2018-10-01 08:35:44

标签: wpf binding

将视图模型绑定到我创建的用户控件时遇到问题。 viewmodel不能反映值的变化。

UpDown.xaml(用户控件xaml部分) btnUp和btnDown用于更改txtNum的文本。我不知道这是对的吗?

<Grid DataContext="{Binding ElementName=btnDownRoot}">
    <Grid.RowDefinitions>
        <RowDefinition Height="0*"/>
        <RowDefinition/>
        <RowDefinition Height="0*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0*"/>
        <ColumnDefinition Width="78*"/>
        <ColumnDefinition Width="104*"/>
        <ColumnDefinition Width="77*"/>
        <ColumnDefinition Width="0*"/>
    </Grid.ColumnDefinitions>
    <TextBox Name="txtNum" Text="{Binding ElementName=btnDownRoot, Path=NumValue}" FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="White" Grid.Column="2" Grid.RowSpan="2"/>
    <Button Name="btnUp" Style="{StaticResource ResourceKey=btnUp}" Click="btnUp_Click" Grid.Column="3" Grid.RowSpan="2"/>
    <Button Name="btnDown" Style="{StaticResource ResourceKey=btnDown}" Click="btnDown_Click" Grid.RowSpan="2" Grid.ColumnSpan="2"/>
</Grid>

UpDown.xaml.cs(用户控制代码部分)

    public string NumValue
    {
        get
        {

            return GetValue(NumValueProperty).ToString();
        }
        set
        {

            SetValue(NumValueProperty, value);
        }
    }

    public static readonly DependencyProperty NumValueProperty =
        DependencyProperty.Register("NumValue", typeof(string), typeof(UpDown), 
            new PropertyMetadata("1", new PropertyChangedCallback(OnNumChanged)));

    private static void OnNumChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
    {
        var instannce = d.ToString();
    }

在MainWindow中,我将MainViewModel绑定到UserControl MainViewModel.cs

public class MainViewModel: BaseViewModel
{
    private string _myValue;
    public string MyValue
    {
        get { return _myValue; }
        set
        {
            _myValue = value;
            OnPropertyChanged("MyValue");

        }
    }
}

MainWindow.xaml

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <local:UpDown Grid.Row="0" NumValue="{Binding MyValue}" x:Name="udGuestNum"  Width="220"  Margin="0 20"/>
    <Button Name="btnOK" Grid.Row="1" Content="OK" Click="btnOK_Click"/>
</Grid>

2 个答案:

答案 0 :(得分:1)

默认情况下,NumValue绑定是OneWay。要么将其明确设置为TwoWay

NumValue="{Binding MyValue, Mode=TwoWay}" 

或将TwoWay设为默认值:

public static readonly DependencyProperty NumValueProperty =
    DependencyProperty.Register(
        "NumValue", typeof(string), typeof(UpDown),
        new FrameworkPropertyMetadata(
            "1", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnNumChanged));

答案 1 :(得分:-1)

数字上/下控件已经开发出来...不要浪费时间,您甚至可以获取代码> https://github.com/xceedsoftware/wpftoolkit