开发者

WPF custom control DependencyProperty won't databind

I have a really simple user control called SetSpeed:

<UserControl x:Class="AGWPFControls.SetSpeed"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             MinHeight="50" MinWidth="110">
    <Canvas>
        <Slider Name="sldSetSpeed" MinWidth="100" Canvas.Top="5" Canvas.Left="5" />
        <TextBox Name="txtSpeed" MinWidth="100" Canvas.Bottom="5" Canvas.Right="5" 
                Text="{Binding ElementName=sldSetSpeed, Path=Value}" />
    </Canvas>
</UserControl>

It has a DependencyProperty called Speed:

public partial class SetSpeed : UserControl
{
    public SetSpeed()
    {
        InitializeComponent();
    }
    public static readonly DependencyProperty SpeedProperty;
    static SetSpeed()
    {
        var md = new FrameworkPropertyMetadata(0.0);
        SetSpeed.SpeedProperty = DependencyProperty.Register(
            "Speed", typeof(double), typeof(SetSpeed), md);
    }
    public double Speed
    {
        get { return (double)GetValue(SetSpeed.SpeedProperty); }
        set { SetValue(SetSpeed.SpeedProperty, value); }
    }
}

I have placed the control i开发者_JS百科n a Window and am binding an element (any element) to it:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" xmlns:my="clr-namespace:AGWPFControls;assembly=AGWPFControls">
    <StackPanel>
        <my:SetSpeed Name="setSpeed1" />
        <TextBlock Text="{Binding ElementName=setSpeed1, Path=Speed}" />
    </StackPanel>
</Window>

Simple as it comes. No dice, though. When I move the slider, the value in the TextBlock never changes. What am I missing, here?


It doesn't look like you have bound your Slider to your dependency property. Something like:

<UserControl x:Name="userControl" x:Class="AGWPFControls.SetSpeed"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             MinHeight="50" MinWidth="110">
    <Canvas>
        <Slider Name="sldSetSpeed" MinWidth="100" Canvas.Top="5" Canvas.Left="5"
                Value="{Binding Speed, ElementName=userControl, Mode=TwoWay}" />
        <TextBox Name="txtSpeed" MinWidth="100" Canvas.Bottom="5" Canvas.Right="5" 
                Text="{Binding ElementName=sldSetSpeed, Path=Value}" />
    </Canvas>
</UserControl>


EDIT: Sorry, was looking at the slider property. :-)

Try Setting your binding Mode to two way:

Also, check your output console to see if there is a binding error. and set a breakpoint on your get method and see if it gets called

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜