【问题标题】:Adding binding to a custom control on windows phone将绑定添加到 Windows Phone 上的自定义控件
【发布时间】:2015-09-11 10:43:00
【问题描述】:

我为一个项目创建了一个自定义图像按钮。这是基于https://code.msdn.microsoft.com/windowsapps/Custom-Image-Button-in-4b300b62 提供的代码。

我已经调整了图像按钮以满足我的需要,它在设计器中看起来不错。但是,我正在尝试使用 DependencyProperty 将文本块绑定到视图模型。

按钮的内脏是这样的

<StackPanel x:Name="Panel" Orientation="Horizontal" VerticalAlignment="Center">
    <Image Margin="10,0,-10,0" x:Name="Image" Width="48" Height="48" Source="/Assets/Images/mappin.png"/>
    <StackPanel Orientation="Vertical" VerticalAlignment="Center">
        <Grid x:Name="LayoutRoot" Background="Transparent">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock Width="400" x:Name="txtHeading" Text="Mooo" Grid.Row="0" TextAlignment="Center" Margin="20,0,-10,0" FontFamily="/TfL.CongestionCharge.WindowsPhone;component/Assets/Fonts/NJFont-Book.ttf#NJFont Book" />
            </Grid>
    </StackPanel>
</StackPanel>

没什么了不起,但可以满足我的需要。

TextBlock 依赖的代码如下所示

public static readonly DependencyProperty TextDependencyProperty = DependencyProperty.Register(
   "Text",
   typeof(string),
   typeof(UserControl),
   new PropertyMetadata(null));

    public string Text
    {
        get
        {
            return GetValue(TextDependencyProperty) as string;
        }

        set
        {
            SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
        }
    }

(我最初遇到了无法从 System.Windows.Bindable 转换为 System.String 错误,此代码将编译但在 setter 中给出了 null ref. 异常)

如果我尝试绑定到 ICommand 或者我可以只使用,我是否需要以正确的方式进行此操作?是否需要创建 DependencyProperty

private ICommand command;
public ICommand Command
    {
        get
        {
            return command;
        }

        set
        {
            command = value;
            command.Execute(value);
        }
    }

【问题讨论】:

    标签: c# windows-phone-8 windows-phone-8.1


    【解决方案1】:

    将您的设置器改为“普通”设置器:

    SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
    

    使用这个:

    SetValue(TextDependencyProperty, value);
    

    给你的UserControl 起个名字:

    <UserControl ... x:Name="thisControl">
    

    在您的TextBlock 中使用绑定到您的控件属性:

    Text="{Binding Text, ElementName=thisControl}"
    

    希望这会有所帮助。

    【讨论】:

    • 确实如此。现在只有两个问题 - 图片没有显示,绑定的文本也没有显示:(
    • 这很奇怪。此更改应该对图像没有影响。您能否提供您的UserControl 的完整 XAML?
    • D'oh 缺少/在资产之前。不确定文本是否不具有约束力:(
    • 在提供的代码中,您的控件中没有依赖属性。此外,您没有从属性定义到文本块和图像的绑定。
    • 第 81 和 87 行具有属性。绑定来自主视图模型(例如 Binding VrmLookupCommand)
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多