【问题标题】:Bind a value from code behind to datatemplate control in wpf将代码后面的值绑定到 wpf 中的数据模板控件
【发布时间】:2017-01-30 05:59:16
【问题描述】:

我是 wpf 的新手,我创建了一个列表框,它将创建一个动态列表项,这里我使用了 datetemplate,它包含两个控件,即两个文本块,一个文本块包含绑定一个值形式的组合框(它是字符串数据类型),另一种是,从代码绑定中绑定一个值。

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)

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

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

在这个类中为小时值创建一个属性。对于这个类,我在下面提到的代码隐藏文件中创建了一个对象。创建一个对象并为 hourvalue 变量赋值。

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");
    }
}

在这里,我为 Rounderhour 类创建了一个对象。将值分配给该属性小时值。但我无法将代码绑定中的值绑定到 XAML 页面。

【问题讨论】:

  • 您的DataContext 需要有一个包含{ get; } (getter)public 属性才能从您的Binding 中获取值。还要注意Roundedhour 中的属性称为hourvalue 而不是roundedhourvalue当遇到绑定问题时,请务必检查 VisualStudio 中的 Output-Window。 - 在那里您会看到缺少的内容...

标签: c# wpf


【解决方案1】:

您的ItemsSource 应该是CollectionType

ListBox ItemsSource="{Binding obj}" 

你也应该开始给你的变量和属性起有意义的名字。这让以后更容易阅读您的代码n。

第二个问题在于您的Binding 本身。

你是这样绑定的:Text="{Binding roundedhourvalue}

所以 WPF 期望 roundedhourvalue 上的属性 obj

但如您的CodeBehind 所示,只有obj.hourvalue

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

详情请查看您的Output-Window

注意:

string roundedhourvalue = obj.hourvalue;

没有getter,并且因为它的private 而无法访问。

注意:您可以使用Binding 在 CodeBehind 中设置 ItemsSource。


试试这样:

只需删除所有格式和内容:

<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>

并将您的代码隐藏更改为:

    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;
    }

或者您可以使用“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
    }

【讨论】:

  • 我更改了 Text={Binding hourvalue} 但值未绑定到标签。
  • 你应该阅读MVVM
  • System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“字符串”(HashCode=-2067273858)上找不到“obj”属性。绑定表达式:路径=obj; DataItem='String' (HashCode=-2067273858);目标元素是'标签'(名称='');目标属性是“内容”(类型“对象”)
【解决方案2】:

将 XAML 对象的“ItemsSource”属性分配给您的绑定变量。

另外,将对象本身绑定到对象的属性中也是完全错误的

this.DataTemplate = this;

用途:

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

这里你可以找到一个例子:

Grid & Pivot Binding Example for multiple DataTemplates

【讨论】:

  • this.ItemsSource = obj;获取 this.ItemsSource 中的值,但该值未绑定到标签
  • 您使用“Listbox”并且它具有必须在代码隐藏中分配的 ItemsSource 属性,并且这无法在您的代码示例中完成:this.DataContext = this;您需要为 itemssource 分配一个 Collection,例如(List、Ienumerable 等)。所以你还没有将任何东西绑定到你的视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 2018-12-08
  • 2015-11-07
  • 2018-11-24
  • 2011-02-15
  • 1970-01-01
  • 2012-08-18
相关资源
最近更新 更多