Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF C# binding code - why doesn't this simple example work?

Tags:

c#

.net

binding

wpf

I've attached some WPF C# binding code - why doesn't this simple example work? (just trying to understanding binding to a custom object). That is when clicking on the button to increase the counter in the model, the label isn't updated.

<Window x:Class="testapp1.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">
    <Grid>
        <Button  Height="23" HorizontalAlignment="Left" Margin="20,12,0,0" 
                 Name="testButton" VerticalAlignment="Top" Width="126" 
                 Click="testButton_Click" Content="Increase Counter" />
        <Label Content="{Binding Path=TestCounter}" Height="37" 
               HorizontalAlignment="Right" Margin="0,12,122,0" 
               Name="testLabel2" VerticalAlignment="Top" 
               BorderThickness="3" MinWidth="200"  />
    </Grid>
</Window>


namespace testapp1
{
    public partial class MainWindow : Window
    {
        public TestModel _model;

        public MainWindow()
        {
            InitializeComponent();

            InitializeComponent();
            _model = new TestModel();
            _model.TestCounter = 0;
            this.DataContext = _model;
        }

        private void testButton_Click(object sender, RoutedEventArgs e)
        {
            _model.TestCounter = _model.TestCounter + 1;
            Debug.WriteLine("TestCounter = " + _model.TestCounter);
        }
    }

    public class TestModel : DependencyObject
    {
        public int TestCounter { get; set; }
    }

}

thanks

like image 828
Greg Avatar asked May 19 '26 06:05

Greg


2 Answers

For this simple example, consider using INotifyPropertyChanged and not DependencyProperties!

UPDATE If you do want to use DPs, use the propdp snippet in VS2010 or Dr WPF's snippets for VS2008?

like image 89
rudigrobler Avatar answered May 21 '26 18:05

rudigrobler


TestCounter needs to be a DepenencyProperty

    public int TestCounter
    {
        get { return (int)GetValue(TestCounterProperty); }
        set { SetValue(TestCounterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for TestCounter.  
    //This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TestCounterProperty =
        DependencyProperty.Register
             ("TestCounter", 
              typeof(int), 
              typeof(TestModel), 
              new UIPropertyMetadata(0));
like image 34
Daniel Avatar answered May 21 '26 20:05

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!