简体   繁体   English

将值从代码后面绑定到wpf中的datatemplate控件

[英]Bind a value from code behind to datatemplate control in wpf

I'm new to wpf, I created a listbox it will create a dynamic listitems,Here I used datetemplate which contains two controls that is two textblocks, one textblocks contains binding a values form combobox(which is string datatype),The other one is, bind a value from code bind. 我是wpf的新手,我创建了一个列表框,它将创建一个动态列表项,这里我使用datetemplate,其中包含两个控件,这两个控件是两个文本块,一个文本块包含绑定组合表(值是字符串数据类型)的值,另一个是,从代码绑定中绑定一个值。

XAML XAML

<ListBox ItemsSource="{Binding obj}"   HorizontalContentAlignment="Left"  x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="201" BorderBrush="#555555" Margin="80,40,0,0" VerticalAlignment="Top" Width="282" Background="#555555" >
    <ListBox.ItemTemplate>
            <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="5" >
                <TextBlock Height="40px" Width="80px" Text="{Binding roundedhourvalue, FontSize="24" Background="#555555"  Foreground="White"></TextBlock>
                <TextBlock x:Name="items"  Text="{Binding}" Margin="35,0,0,0"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

C# (Roundedhour.cs) C#(Roundedhour.cs)

public class Roundedhour
{
    public string hourvalue { get; set; }

    public override string ToString()
    {
       return string.Format("{0}", hourvalue);
    }
} 

In this class create a property for hourvalue. 在此类中,为hourvalue创建一个属性。 For this class I created a object in codebehind file which I mentioned below.create a object and assign a value for hourvalue variable. 对于这个类,我在下面提到的代码隐藏文件中创建了一个对象。创建一个对象并为hourvalue变量分配一个值。

C# (Code Behind) C#(后面的代码)

{
    if (dispatcherTimer1.Interval == TimeSpan.FromSeconds(15))
    {
        //lstbxindex.Items.Add(lstbxindex.SelectedItem.ToString());

        string hrvalue = Convert.ToString(hrvalueinitially);  

        obj = new Roundedhour();
        obj.hourvalue = Convert.ToString(hrvalueinitially);

        string roundedhourvalue =obj.hourvalue;

        this.DataContext = this;


        //lblprojectAhr.Content = string.Join(",", hrvalueinitially + "" + "hr");
    }
}

Here, I created a object for Rounderhour class.Assign values to that property hour value. 在这里,我为Rounderhour类创建了一个对象,将值分配给该属性小时值。 But I cannot be bind a value from codebind to XAML page. 但是我不能将值从codebind绑定到XAML页面。

Your ItemsSource should be of an CollectionType . 您的ItemsSource应该是CollectionType

ListBox ItemsSource="{Binding obj}" 

You should also start to give your variables and properties meaningful names. 您还应该开始给变量和属性赋予有意义的名称。 That makes it easier to read your code later o n. 这使以后阅读代码变得更容易

The second Problem is in your Binding itself. 第二个问题在于Binding本身。

You are binding like this: Text="{Binding roundedhourvalue} 您像这样进行绑定: Text="{Binding roundedhourvalue}

So WPF is expecting a property roundedhourvalue on obj . 因此WPF期望obj的属性roundedhourvalue

But as shown in your CodeBehind there is only obj.hourvalue . 但是,如您的CodeBehind所示,只有obj.hourvalue

So change your Binding to Text="{Binding hourvalue} 因此,将您的Binding更改为Text="{Binding hourvalue}

Check your Output-Window for details. 检查Output-Window以获取详细信息。

NOTE: 注意:

string roundedhourvalue = obj.hourvalue;

has no getter and is not accsessible since its private . 没有getter ,因为它是private ,所以不可控。

NOTE : You either use a Binding OR your set the ItemsSource in CodeBehind. 注意 :您要么使用Binding 选择自己设置的的ItemsSource的代码隐藏。


Try it like this: 像这样尝试:

Just remove all the formatting and stuff: 只需删除所有格式和内容:

<ListBox ItemsSource="{Binding RoundedHours}" x:Name="ListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="5" >
               <TextBlock Text="{Binding hourvalue}"></TextBlock>                   
            </StackPanel>
       </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And change your code-behind to this: 然后将您的代码更改为此:

    private void UpdateDataContext(object hrvalueinitially)
    {
        List<Roundedhour> hours = new List<Roundedhour>();
        hours.Add(new Roundedhour()
        {
            hourvalue = hrvalueinitially.ToString()
        });

        //Set the ItemsSource in code: => remove your ItemsSource Binding from XAML
        listBox.ItemsSource = hours;
    }

OR your can use an 'MVVM' approach: 或者您可以使用“ MVVM”方法:

    public class MyViewModel : INotifyPropertyChanged
    {
        //IMPLEMENT INotifyPropertyChanged HERE PLS

        public ObservableCollection<RoundedHour> Collection { get; set; } = new ObservableCollection<RoundedHour>();

        private void AddToCollection(object hrvalueinitially)
        {
            Collection.Add(new RoundedHour()
            {
                hourvalue = hrvalueinitially.ToString()
            });
            OnPropertyChanged("Collection");
        }

        //Make sure to set your Windows DataContext to an Instance of this Class
    }

Assign XAML object's "ItemsSource" property with your binding variable. 为XAML对象的“ ItemsSource”属性分配绑定变量。

Also it's totally wrong binding object's itself into object's property like 而且将对象本身绑定到对象的属性中是完全错误的,例如

this.DataTemplate = this;

Use: 采用:

List<yourobject> bindingObjectList = new List<yourobject>();
// insert your objects into the list
this.ItemsSource = bindingObjectList;

Here you can find an example: 在这里您可以找到一个例子:

Grid & Pivot Binding Example for multiple DataTemplates 多个数据模板的网格和数据透视图绑定示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM