1

I have a very simple WPF Application which has a slider and a button. I am trying to bind one of the properties in my class to the value of the slider and displaying the value in a messagebox whenever the button is clicked.

I have a property called BattingForm in my Player class

<Window.Resources>

    <local:Player x:Key="_batsman" x:Name="_batsman"
                  BattingForm="{Binding Path=Value, ElementName=Form}">
    </local:Player>

</Window.Resources>

<Slider Maximum="1" LargeChange="0.25" Value="0.25" Name="Form"/>

And inside the Player Class, the property is as follows.

    public double BattingForm
    {
        get { return (double)GetValue(BattingFormProperty); }
        set { SetValue(BattingFormProperty, value); }
    }

    public static readonly DependencyProperty BattingFormProperty =
        DependencyProperty.Register("BattingForm", typeof(double), typeof(Player));

And in the MainWindow.xaml.cs inside the buttonclick event, I try to access it as follows -

        Player batsman = FindResource("_batsman") as Player;
        if(batsman!=null)
        {
           MessageBox.Show(batsman.BattingForm.ToString());
        }

In the MessageBox it only shows 0, not the actual value of the Slider.

4

3 回答 3

2

Player在实际使用之前,控件不会发生数据绑定。目前,您只声明了您的_batsman资源,但并未实际使用它。

正如您所说,您只是为了测试而这样做,最简单的做法是Player从可在 XAML 中使用的基类派生,例如Control

public class Player : Control

然后您将能够在 XAML 中执行此操作:

<StackPanel>
    <Slider Maximum="1" LargeChange="0.25" Value="0.25" Name="Form"/>

    <local:Player x:Name="_batsman"
                  BattingForm="{Binding Path=Value, ElementName=Form}" />
</StackPanel>
于 2013-05-25T20:50:18.553 回答
2

您可以轻松地在 Slider 而不是 Player 资源上声明绑定:

<Window.Resources>
    <local:Player x:Key="batsman" BattingForm="0.25"/>
</Window.Resources>
<Grid>
    <Slider Maximum="1" LargeChange="0.25"
            Value="{Binding BattingForm, Source={StaticResource batsman}}"/>
</Grid>

这是因为ValueSlider 的属性默认是双向绑定的。如果它不这样做,则必须明确设置 TwoWay 模式:

<Slider Maximum="1" LargeChange="0.25"
        Value="{Binding BattingForm, Source={StaticResource batsman}, Mode=TwoWay}"/>
于 2013-05-25T20:50:29.693 回答
2

尝试反转您的绑定:

<Window.Resources>
    <local:Player x:Key="_batsman" BattingForm="0.25" />
</Window.Resources>
<Grid>
    <StackPanel>
        <Slider Maximum="1.0" LargeChange="0.25" Value="{Binding BattingForm, Source={StaticResource _batsman}}" />
        <!-- Included for testing -->
        <TextBox Text="{Binding BattingForm, Source={StaticResource _batsman}}" />
    </StackPanel>
</Grid>
于 2013-05-25T20:58:01.563 回答