如何通过传递参数将文本绑定到文本块

时间:2015-05-20 19:16:04

标签: c# wpf xaml mvvm

在下面根据问题ID的代码中,bordercolor将以我想要根据问题ID更改文本框文本值的相同方式更改,如何在MVVM中

<Border CornerRadius="50" Grid.Column="0" Margin="5,2,0,0" VerticalAlignment="Top"
        Width="21" Height="21" Padding="0,2,0,0"                                             
        Background="{Binding Question.ID, Converter={StaticResource QuestionIdToBorderColorConverter}}">
        <TextBlock HorizontalAlignment="Center" FontWeight="SemiBold"
                   FontSize="12" Foreground="Black" 
                   Text="{Binding SequenceNumber}" />
</Border>

1 个答案:

答案 0 :(得分:0)

我认为你想要绑定的数据需要在一个Viewmodel中:

public class Question : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        OnPropertyChangedExplicit(propertyName);
    }

    protected void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> projection)
    {
        var memberExpression = (MemberExpression)projection.Body;
        OnPropertyChangedExplicit(memberExpression.Member.Name);
    }

    void OnPropertyChangedExplicit(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    int _id = false;
    public int id
    {
        get { return _id; }
        set { if (value != _id) { _id= value; OnPropertyChanged(); } }
    }
    string _sequencenumber = false;
    public int SequenceNumber 
    {
        get { return _sequencenumber ; }
        set { if (value != _sequencenumber ) { _sequencenumber = value; OnPropertyChanged(); } }
    }
}

在CodeBehind中设置Border的DataContext

Question = new Question();
MyBorder.DataContext = question;

<Border x:Name="MyBorder" CornerRadius="50" Grid.Column="0" Margin="5,2,0,0" VerticalAlignment="Top"
                        Width="21" 
                        Height="21" Padding="0,2,0,0"                                             
                        Background="{Binding Question.ID, Converter={StaticResource QuestionIdToBorderColorConverter}}">
                <TextBlock HorizontalAlignment="Center" FontWeight="SemiBold" FontSize="12" Foreground="Black" Text="{Binding Question.SequenceNumber}" />
            </Border>

我希望有帮助...