24

Silverlight 3.0 アプリケーションで、キャンバスに四角形を作成し、キャンバスの幅全体に広げようとしています。親コンテナーのプロパティにバインドすることでこれを実行しようとしましたがActualWidth(以下のサンプルを参照)、バインド エラーは表示されませんが、値はバインドされていません。幅が 0 であるため、四角形は表示されません。さらにActualWidth、長方形を含むキャンバスの にバインドしようとしましたが、違いはありませんでした。

このバグが Microsoft Connect に記録されていることは確認しましたが、回避策は記載されていませんでした。

誰かがこの問題を解決できましたか、または解決策を指摘できますか?

編集:元のコード サンプルは、私が達成しようとしているものとは正確ではなく、より明確にするために更新されました。

<UserControl>
    <Border BorderBrush="White"
            BorderThickness="1"
            CornerRadius="4"
            HorizontalAlignment="Center">
        <Grid x:Name="GridContainer">
            <Rectangle Fill="Aqua"
                       Width="150"
                       Height="400" />
            <Canvas>
                <Rectangle Width="{Binding Path=ActualWidth, ElementName=GridContainer}"
                           Height="30"
                           Fill="Red" />
            </Canvas>

            <StackPanel>
                <!-- other elements here -->
            </StackPanel>
        </Grid>
    </Border>
</UserControl>
4

8 に答える 8

32

プロパティにデータバインドする必要があることを何をしようとしていActualWidthますか? これは Silverlight の既知の問題であり、簡単な回避策はありません。

できることの 1 つは、Rectangle の幅を実際に設定する必要がないようにビジュアル ツリーを設定し、適切なサイズに拡大できるようにすることです。上記の例で、Canvas を削除 (または Canvas を他の Panel に変更) し、 を に設定したままRectangleHorizontalAlignmentするStretchと、使用可能な幅 (実質的には Grid の幅) がすべて使用されます。

ただし、これは特定のケースでは不可能な場合があり、データバインディングを設定する必要がある場合があります。これが直接不可能であることはすでに確立されていますが、プロキシ オブジェクトの助けを借りて、必要なバインドを設定できます。次のコードを検討してください。

public class ActualSizePropertyProxy : FrameworkElement, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public FrameworkElement Element
    {
        get { return (FrameworkElement)GetValue(ElementProperty); }
        set { SetValue(ElementProperty, value); }
    }

    public double ActualHeightValue
    {
        get{ return Element == null? 0: Element.ActualHeight; }
    }

    public double ActualWidthValue
    {
        get { return Element == null ? 0 : Element.ActualWidth; }
    }

    public static readonly DependencyProperty ElementProperty =
        DependencyProperty.Register("Element", typeof(FrameworkElement), typeof(ActualSizePropertyProxy), 
                                    new PropertyMetadata(null,OnElementPropertyChanged));

    private static void OnElementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((ActualSizePropertyProxy)d).OnElementChanged(e);
    }

    private void OnElementChanged(DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement oldElement = (FrameworkElement)e.OldValue;
        FrameworkElement newElement = (FrameworkElement)e.NewValue;

        newElement.SizeChanged += new SizeChangedEventHandler(Element_SizeChanged);
        if (oldElement != null)
        {
            oldElement.SizeChanged -= new SizeChangedEventHandler(Element_SizeChanged);
        }
        NotifyPropChange();
    }

    private void Element_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        NotifyPropChange();
    }

    private void NotifyPropChange()
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("ActualWidthValue"));
            PropertyChanged(this, new PropertyChangedEventArgs("ActualHeightValue"));
        }
    }
}

これを xaml で次のように使用できます。

<Grid x:Name="LayoutRoot">
    <Grid.Resources>
        <c:ActualSizePropertyProxy Element="{Binding ElementName=LayoutRoot}" x:Name="proxy" />
    </Grid.Resources>
    <TextBlock x:Name="tb1" Text="{Binding ActualWidthValue, ElementName=proxy}"  />
</Grid>

そのため、TextBlock.Text をプロキシ オブジェクトの ActualWidthValue にバインドしています。プロキシ オブジェクトは、Element の ActualWidth を提供します。これは、別の Binding によって提供されます。

これは問題に対する単純な解決策ではありませんが、ActualWidth にデータバインドする方法について私が考えることができる最善の方法です。

シナリオをもう少し説明すると、より簡単な解決策を思いつくことができるかもしれません。DataBinding はまったく必要ない場合があります。SizeChanged イベント ハンドラーのコードからプロパティを設定することは可能でしょうか?

于 2009-10-22T02:03:31.400 に答える
21

添付プロパティのメカニズムを使用して、ActualHeightイベントActualWidthによって更新されるプロパティをSizeChanged定義できます。その使用法は次のようになります。

<Grid local:SizeChange.IsEnabled="True" x:Name="grid1">...</Grid>

<TextBlock Text="{Binding ElementName=grid1,
                         Path=(local:SizeChange.ActualHeight)}"/>

技術的な詳細は、次の場所にあります。

http://darutk-oboegaki.blogspot.com/2011/07/binding-actualheight-and-actualwidth.html

他のソリューションと比較したこのソリューションの利点は、ソリューションで定義された添付プロパティ (SizeChange.ActualHeight および SizeChange.ActualWidth) を、サブクラスを作成せずに任意の FrameworkElement に使用できることです。このソリューションは再利用可能で、侵襲性が低くなります。


リンクが古くなった場合、リンクに示されている SizeChange クラスは次のとおりです。

// Declare SizeChange class as a sub class of DependencyObject

// because we need to register attached properties.
public class SizeChange : DependencyObject
 {
     #region Attached property "IsEnabled"

    // The name of IsEnabled property.
    public const string IsEnabledPropertyName = "IsEnabled";

    // Register an attached property named "IsEnabled".
    // Note that OnIsEnabledChanged method is called when
    // the value of IsEnabled property is changed.
    public static readonly DependencyProperty IsEnabledProperty
         = DependencyProperty.RegisterAttached(
             IsEnabledPropertyName,
             typeof(bool),
             typeof(SizeChange),
             new PropertyMetadata(false, OnIsEnabledChanged));

    // Getter of IsEnabled property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static bool GetIsEnabled(DependencyObject obj)
     {
         return (bool)obj.GetValue(IsEnabledProperty);
     }

    // Setter of IsEnabled property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static void SetIsEnabled(DependencyObject obj, bool value)
     {
         obj.SetValue(IsEnabledProperty, value);
     }

     #endregion

     #region Attached property "ActualHeight"

    // The name of ActualHeight property.
    public const string ActualHeightPropertyName = "ActualHeight";

    // Register an attached property named "ActualHeight".
    // The value of this property is updated When SizeChanged
    // event is raised.
    public static readonly DependencyProperty ActualHeightProperty
         = DependencyProperty.RegisterAttached(
             ActualHeightPropertyName,
             typeof(double),
             typeof(SizeChange),
             null);

    // Getter of ActualHeight property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static double GetActualHeight(DependencyObject obj)
     {
         return (double)obj.GetValue(ActualHeightProperty);
     }

    // Setter of ActualHeight property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static void SetActualHeight(DependencyObject obj, double value)
     {
         obj.SetValue(ActualHeightProperty, value);
     }

     #endregion

     #region Attached property "ActualWidth"

    // The name of ActualWidth property.
    public const string ActualWidthPropertyName = "ActualWidth";

    // Register an attached property named "ActualWidth".
    // The value of this property is updated When SizeChanged
    // event is raised.
    public static readonly DependencyProperty ActualWidthProperty
         = DependencyProperty.RegisterAttached(
             ActualWidthPropertyName,
             typeof(double),
             typeof(SizeChange),
             null);

    // Getter of ActualWidth property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static double GetActualWidth(DependencyObject obj)
     {
         return (double)obj.GetValue(ActualWidthProperty);
     }

    // Setter of ActualWidth property. The name of this method
    // should not be changed because the dependency system
    // uses it.
    public static void SetActualWidth(DependencyObject obj, double value)
     {
         obj.SetValue(ActualWidthProperty, value);
     }

     #endregion

    // This method is called when the value of IsEnabled property
    // is changed. If the new value is true, an event handler is
    // added to SizeChanged event of the target element.
    private static void OnIsEnabledChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
     {
        // The given object must be a FrameworkElement instance,
        // because we add an event handler to SizeChanged event
        // of it.
        var element = obj as FrameworkElement;

         if (element == null)
         {
            // The given object is not an instance of FrameworkElement,
            // meaning SizeChanged event is not available. So, nothing
            // can be done for the object.
            return;
         }

        // If IsEnabled=True
        if (args.NewValue != null && (bool)args.NewValue == true)
         {
             // Attach to the element.
             Attach(element);
         }
         else
         {
             // Detach from the element.
             Detach(element);
         }
     }

     private static void Attach(FrameworkElement element)
     {
        // Add an event handler to SizeChanged event of the element

        // to take action when actual size of the element changes.
        element.SizeChanged += HandleSizeChanged;
     }

     private static void Detach(FrameworkElement element)
     {
        // Remove the event handler from the element.
        element.SizeChanged -= HandleSizeChanged;
     }

    // An event handler invoked when SizeChanged event is raised.
    private static void HandleSizeChanged(object sender, SizeChangedEventArgs args)
     {
         var element = sender as FrameworkElement;

         if (element == null)
         {
             return;
         }

        // Get the new actual height and width.
        var width  = args.NewSize.Width;
         var height = args.NewSize.Height;

        // Update values of SizeChange.ActualHeight and

        // SizeChange.ActualWidth.
        SetActualWidth(element, width);
         SetActualHeight(element, height);
     }
 }
于 2011-07-28T16:44:23.043 に答える
9

私の解決策は、RealWidth と呼ばれる自分自身を宣言し、イベントDependencyPropertyでその値を更新することです。SizeChangedその後、プロパティとは異なり、更新される RealWidth にバインドできActualWidthます。

public MyControl()
{
    InitializeComponent();
    SizeChanged += HandleSizeChanged;
}

public static DependencyProperty RealWidthProperty =
     DependencyProperty.Register("RealWidth", typeof (double),
     typeof (MyControl),
     new PropertyMetadata(500D));

public double RealWidth
{
    get { return (double) GetValue(RealWidthProperty); }
    set { SetValue(RealWidthProperty, value); }
}

private void HandleSizeChanged(object sender, SizeChangedEventArgs e)
{
    RealWidth = e.NewSize.Width;
}
于 2010-11-14T23:34:52.907 に答える
5

ContentPresenterから継承し、実際に現在のサイズを提供できる単純なパネル コントロールを作成してみませんか。

public class SizeNotifyPanel : ContentPresenter
{
    public static DependencyProperty SizeProperty =
        DependencyProperty.Register("Size",
                                    typeof (Size),
                                    typeof (SizeNotifyPanel),
                                    null);

    public Size Size
    {
        get { return (Size) GetValue(SizeProperty); }
        set { SetValue(SizeProperty, value); }
    }

    public SizeNotifyPanel()
    {
        SizeChanged += (s, e) => Size = e.NewSize;
    }
}

その後、実際のコンテンツのラッパーとして使用する必要があります。

<local:SizeNotifyPanel x:Name="Content">
    <TextBlock Text="{Binding Size.Height, ElementName=Content}" />
</local:SizeNotifyPanel>

魅力のように私のために働き、きれいに見えます。

于 2011-10-12T08:56:13.763 に答える
2

@darutk's answerに基づいて、非常にエレガントに機能する添付のプロパティベースのソリューションを次に示します。

public static class SizeBindings
{
    public static readonly DependencyProperty ActualHeightProperty =
        DependencyProperty.RegisterAttached("ActualHeight", typeof (double), typeof (SizeBindings),
                                            new PropertyMetadata(0.0));

    public static readonly DependencyProperty ActualWidthProperty =
        DependencyProperty.RegisterAttached("ActualWidth", typeof (Double), typeof (SizeBindings),
                                            new PropertyMetadata(0.0));

    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached("IsEnabled", typeof (bool), typeof (SizeBindings),
                                            new PropertyMetadata(false, HandlePropertyChanged));

    private static void HandlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = d as FrameworkElement;
        if (element == null)
        {
            return;
        }

        if ((bool) e.NewValue == false)
        {
            element.SizeChanged -= HandleSizeChanged;
        }
        else
        {
            element.SizeChanged += HandleSizeChanged;
        }
    }

    private static void HandleSizeChanged(object sender, SizeChangedEventArgs e)
    {
        var element = sender as FrameworkElement;

        SetActualHeight(element, e.NewSize.Height);
        SetActualWidth(element, e.NewSize.Width);
    }

    public static bool GetIsEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsEnabledProperty);
    }

    public static void SetIsEnabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsEnabledProperty, value);
    }

    public static Double GetActualWidth(DependencyObject obj)
    {
        return (Double) obj.GetValue(ActualWidthProperty);
    }

    public static void SetActualWidth(DependencyObject obj, Double value)
    {
        obj.SetValue(ActualWidthProperty, value);
    }

    public static double GetActualHeight(DependencyObject obj)
    {
        return (double)obj.GetValue(ActualHeightProperty);
    }

    public static void SetActualHeight(DependencyObject obj, double value)
    {
        obj.SetValue(ActualHeightProperty, value);
    }
}

次のように使用します。

    <Grid>
        <Border x:Name="Border" behaviors:SizeBindings.IsEnabled="True"/>
        <Border MinWidth="{Binding (behaviors:SizeBindings.ActualWidth), ElementName=Border}"/>
    </Grid>
于 2013-03-29T10:59:28.080 に答える
1

TestConverter を使用して公開している更新された xaml をテストして、幅に渡される値を確認し、それが機能していることを確認しました (私は VS 2010 B2 を使用しています)。TestConverter を使用するには、Convert メソッドにブレークポイントを設定するだけです。

    public class TestConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

    }

値 150 が渡され、Rectangle の幅は 150 でした。

何か違うことを期待していましたか?

于 2009-10-21T18:17:01.717 に答える
0

これはActualWidth .

私のプロセスは変更イベントを必要としませんでした。現在の状態の値の最終結果が必要でした。Targetそこで、カスタム コントロール/プロセスで呼び出される依存関係プロパティを として作成しFrameworkElement、消費者 xaml が問題の実際のオブジェクトにバインドします。

計算の時間になると、コードは実際のオブジェクトを取得して抽出できますActualWidth


コントロールの依存関係プロパティ

public FrameworkElement Target
{
    get { return (FrameworkElement)GetValue(TargetProperty);}
    set { SetValue(TargetProperty, value);}
}

// Using a DependencyProperty as the backing store for Target.
// This enables animation, styling, binding, general access etc...
public static readonly DependencyProperty TargetProperty =
    DependencyProperty.Register("Target", typeof(FrameworkElement), 
                                typeof(ThicknessWrapper), 
                                new PropertyMetadata(null, OnTargetChanged));

Rectangle へのバインディングを示す Consumer 側の XAML

<local:ThicknessWrapper Target="{Binding ElementName=thePanel}"/>

<Rectangle x:Name="thePanel" HorizontalAlignment="Stretch" Height="20"  Fill="Blue"/>

取得コード

double width;

if (Target != null)
   width = Target.ActualWidth;  // Gets the current value.
于 2015-07-17T13:22:00.543 に答える
0

KeithMahoneyの回答に基づいて、UWP アプリで問題なく動作し、問題を解決します。ただし、 ActualWidthValueActualHeightValueの両方の初期値が設計時に提供されないため、設計時にコントロールを表示できません。実行時には問題なく動作しますが、コントロールのレイアウトを設計するには不便です。少し変更するだけで、この問題は解決できます。

  1. ActualWidthValueActualHeightValueの両方のプロパティの c# コードに、次のように追加します。

    設定 {;}

    XAML コードからダミーの値を提供できるようにします。実行時には使用しませんが、設計時には使用できます。

  2. 彼の XAML コードのResourcesの宣言で、 c:ActualSizePropertyProxyに適切な ActualWidthValue および ActualHeightValue の値を提供ます

    ActualHeightValue="800" ActualWidthValue="400"

    次に、設計時に 400x800 のコントロールが表示されます。

于 2016-10-14T04:13:56.033 に答える