将Textblock与datacontext代码绑定绑定

时间:2015-07-22 07:06:35

标签: c# wpf binding code-behind

我想绑定从后面的代码动态生成的边框。

下面是我与边框绑定的模型。

public class MapTextboxGridModel : INotifyPropertyChanged
{
    private MaptextBoxGridStylePropertiesModel _GridStyleProperties = new MaptextBoxGridStylePropertiesModel();
    public MaptextBoxGridStylePropertiesModel GridStyleProperties
    {
        get { return _GridStyleProperties; }
        set
        {
            _GridStyleProperties = value;
            OnPropertyChanged("GridStyleProperties");
        }
    }
}

每个单元格的样式都在_GridStyleProperties中。在_GridStyleProperties模型中,我有一个属性" _Name"如下。

public class MaptextBoxGridStylePropertiesModel : INotifyPropertyChanged
{
private string _Name = "Enter your text";
public string Name
{
    get { return _Name; }
    set
    {
        _Name = value;
        OnPropertyChanged("Name");
    }
}}


// following border(multiple, so I will have border in each cell of the grid) is created inside a grid


MapTextboxGridModel cellcontext = new MapTextboxGridModel();
Border db = new Border();
db.MouseLeftButtonDown += db_MouseLeftButtonDown;
db.DataContext = cellcontext;
TextBlock block = new TextBlock() { Text = cellcontext.GridStyleProperties.Name };

然后当我点击网格中的任何一个单元格时。

void db_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (columnpossition == -1 && rowpossition == -1)
        {
            columnpossition = Grid.GetColumn(sender as Border);
            rowpossition = Grid.GetRow(sender as Border);
        }
        else
        {
            Border bod = sender as Border;
            Grid grd = bod.Parent as Grid;
            int col = Grid.GetColumn(bod);
            int row = Grid.GetRow(bod);
            if (col == columnpossition && row == rowpossition)
            {
            }
            else
            {
                TextBlock dbtxt = bod.Child as TextBlock;
                imodel.GridStyleProperties.needtoshow = true;
                Binding textbnd = new Binding();
                textbnd.Source = bod.DataContext as MapTextboxGridModel;
                textbnd.Path = new PropertyPath("StyleProperties.Name"); // Is this possible
                BindingOperations.SetBinding(dbtxt, TextBlock.TextProperty, textbnd);
                columnpossition = col;
                rowpossition = row;
            }
        }
    }

我无法理解我在哪里弄错了。请建议我在上面的代码中应该做些什么改变。

0 个答案:

没有答案