XAML, C# novice and am struggling to databind a variable defined in my code behind to a textblock defined in XAML. But I get not result.
Here is my 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>
Here is my code behind
namespace WpfApplication1
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
        var listlength = 100;
    }
}
}
For now I have just set the variable to a static number for the purposes of illustrating my problem but this variable will be obtained from a list Count value.
For binding you need to use Property only .you cannot use varibale for binding.
To create property I have created a class here . It is not necessary to create a new class to have property.
  public class TextboxText
{
    public string textdata { get; set; }
}
And set datacontext to textblock so that I can use this property for binding
InitializeComponent();
totalRecording.DataContext = new TextboxText() { textdata = "100" };
in xaml
<Grid Height="300" Width="400" Background="Red">
    <TextBlock Name="totalRecording">
       <Run Text="44 /"/>
       <Run Text="{Binding textdata}"/>
    </TextBlock>
</Grid
                        If you want to update the Binding, you should use a DependencyProperty.
First you have to create the property and a public string like this:
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); }
    }
Here is the XAML file, you need to set a name for the window:
<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>
Now you can always update the Binding by setting the ListLength like this:
ListLength = "100";
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With