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

本文关键字:绑定 textblock 文本 何通过 参数 | 更新日期: 2023-09-27 17:50:00

在下面的代码中,根据问题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>

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

我认为你想要绑定的数据需要在一个视图模型:

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>