XAML绑定值

时间:2014-12-25 14:04:41

标签: c# wpf xaml binding

我正在开发Windows Phone 8.1应用程序,我需要循环进度条。

我有这个用户控制代码:

<UserControl.Resources>
  <Style TargetType="ProgressBar" x:Key="CircularProgressBarStyle">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ProgressBar">
          <Grid x:Name="LayoutRoot">
            <local:CircularProgressBarViewModel.Attach>
              <local:CircularProgressBarViewModel HoleSizeFactor="0.75"/>
            </local:CircularProgressBarViewModel.Attach>
            <Ellipse Width="{Binding Diameter}" Height="{Binding Diameter}"
                       HorizontalAlignment="Center" VerticalAlignment="Center"
                       Stroke="LightGray" Opacity="0.5" Fill="Transparent"
                       StrokeThickness="10">
          </Ellipse>
            <local:PiePiece CentreX="{Binding CentreX}" CentreY="{Binding CentreY}"
                              RotationAngle="0" WedgeAngle="{Binding Angle}"
                              Radius="{Binding Radius}" InnerRadius="{Binding InnerRadius}"
                              Fill="Black" Opacity="0.7"/>
            <Grid util:GridUtils.RowDefinitions="*,2*,*"
                    util:GridUtils.ColumnDefinitions="*,2*,*">
              <Viewbox Grid.Row="1" Grid.Column="1">
                <TextBlock Name="myValue" Text="{myValue value}"
                             Foreground="WhiteSmoke"
                             FontWeight="Bold"
                             VerticalAlignment="Center" HorizontalAlignment="Center"/>
              </Viewbox>
            </Grid></Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </UserControl.Resources>

如何从后面的代码(例如,从MainPage.xaml.cs)更改名称为“myValue”的值,而不是从CircularProgressBarViewModel更改?

1 个答案:

答案 0 :(得分:1)

如果您需要从主页获取myValue,使用UserControl,您可以在控件中创建DependencyProperty并设置从页面到控件的任何值。

public sealed partial class YourUserControl: UserControl
{
    public static readonly DependencyProperty myValueProperty = DependencyProperty.Register("myValue", typeof(string), typeof(YourUserControl), new PropertyMetadata(string.Empty));

    public YourUserControl()
    {
        this.InitializeComponent();
    }

    public string myValue
    {
        get { return (string)GetValue(myValueProperty ); }
        set { SetValue(myValueProperty , value); }
    }
}

在您的主页上,像这样:

<controls:YourUserControl myValue={Binding YourValue}/>