[英]Databinding a variable in C# to a textblock in a WPF application not working
XAML、C# 新手,并且正在努力将我的代码中定义的变量数据绑定到 XAML 中定义的文本块。 但我没有得到结果。
这是我的 XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded_1">
<Grid>
<TextBlock Name="totalRecording">
<Run Text="44 /"/>
<Run Text="{Binding Source=listlength, Path=totalRecording}"/>
</TextBlock>
</Grid>
这是我的代码
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
var listlength = 100;
}
}
}
现在,为了说明我的问题,我只是将变量设置为静态数字,但该变量将从列表 Count 值中获取。
对于绑定,您只需要使用Property 。您不能使用变量进行绑定。
为了创建属性,我在这里创建了一个类。 没有必要创建一个新类来拥有属性。
public class TextboxText
{
public string textdata { get; set; }
}
并将 datacontext 设置为 textblock 以便我可以使用此属性进行绑定
InitializeComponent();
totalRecording.DataContext = new TextboxText() { textdata = "100" };
在 xaml 中
<Grid Height="300" Width="400" Background="Red">
<TextBlock Name="totalRecording">
<Run Text="44 /"/>
<Run Text="{Binding textdata}"/>
</TextBlock>
</Grid
如果要更新绑定,则应使用DependencyProperty 。
首先,您必须像这样创建属性和公共字符串:
public static readonly DependencyProperty ListLengthProperty =
DependencyProperty.Register("ListLength", typeof(string), typeof(Window), new PropertyMetadata(null));
public string ListLength
{
get { return (string)GetValue(ListLengthProperty); }
set { SetValue(ListLengthProperty, value); }
}
这是XAML文件,您需要为窗口设置一个名称:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="CurrentWindow"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded_1">
<Grid>
<TextBlock Name="totalRecording">
<Run Text="44 /"/>
<Run Text="{Binding ListLength, ElementName=CurrentWindow}"/>
</TextBlock>
</Grid>
现在,您始终可以通过像这样设置ListLength来更新绑定:
ListLength = "100";
只需使用TextBlock,
<Grid Name="myGrid" Height="437.274">
<TextBox Text="{Binding Path=listlength}"/>
</Grid>
声明变量并实现InotifyPropertyChanged
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _listlength;
public string Listlength
{
get { return _listlength; }
set
{
if (value != _listlength)
{
_listlength = value;
OnPropertyChanged("Listlength");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.