Silverlight: Как получить уведомление об изменении в наследованном DependencyProperty

Отредактируйте новое решение:

// write this in your main page
String onMainPageText;

вы можете отобразить это в на своей главной странице! после нажатия кнопки okey в вашем методе _showdialog Text(onMainPageText)

измените ваш метод _showDialog с помощью следующего кода.

  void _showDialog() {
    String dialogText;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: TextField(
            onChanged: (String textTyped) {
              setState(() {
                dialogText = textTyped;
              });
            },
            keyboardType: TextInputType.number,
            decoration: InputDecoration(hintText: 'Enter the number'),
          ),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            Row(
              children: <Widget>[
                new FlatButton(
                  child: new Text("Cancel"),
                  onPressed: () {
                    setState(() {
                      onMainPageText = '';
                    });
                    Navigator.of(context).pop();
                  },
                ),
                new FlatButton(
                    onPressed: () {
                      setState(() {
                        onMainPageText = dialogText;
                      });
                      Navigator.of(context).pop();
                    },
                    child: new Text("OK"))
              ],
            ),
          ],
        );
      },
    );
  }

Старый ответ:

создайте глобальный TextEditingController, который решит вашу проблему. Вы можете получить доступ к тексту текстового поля с помощью textEditingConroller.text

, не забудьте определить textEditingController внутри вашего класса

class YourMainPageState extends State<YourMainPage>{
  TextEditingController textEditingController = new TextEditingController();

}
  void _showDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: TextField(
            controller: textEditingController,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(hintText: 'Enter the number'),
          ),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            Row(
              children: <Widget>[
                new FlatButton(
                  child: new Text("Cancel"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                new FlatButton(onPressed: () {print(textEditingController.text);}, child: new Text("OK"))
              ],
            ),
          ],
        );
      },
    );
  }

Вы можете отобразить напечатанный текст с этим кодом:

Padding(
                padding: const EdgeInsets.only(top: 50.0),
                  child: new Text(texEditingController.text););
12
задан MojoFilter 7 May 2009 в 03:21
поделиться

5 ответов

Думаю, вот способ получше. Все еще нужно увидеть плюсы и минусы.

 /// Listen for change of the dependency property
    public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
    {

        //Bind to a depedency property
        Binding b = new Binding(propertyName) { Source = element };
        var prop = System.Windows.DependencyProperty.RegisterAttached(
            "ListenAttached"+propertyName,
            typeof(object),
            typeof(UserControl),
            new System.Windows.PropertyMetadata(callback));

        element.SetBinding(prop, b);
    }

И теперь вы можете вызвать RegisterForNotification, чтобы зарегистрироваться для получения уведомления об изменении свойства элемента, например.

RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));

См. Мой пост здесь на том же http: / /amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html

Использование Silverlight 4.0 beta.

16
ответ дан 26 October 2019 в 10:46
поделиться

Вы не можете извне прослушивать уведомления об изменениях свойств зависимостей.

Вы можете получить доступ к метаданным свойства зависимостей со следующей строкой кода:

PropertyMetadata metaData = Control.ActualHeightProperty.GetMetadata(typeof(Control));

Тем не менее, единственный открытый элемент, который отображается "DefaultValue".

Существует множество способов сделать это в WPF. Но в настоящее время они не поддерживаются Silverlight 2 или 3.

0
ответ дан 26 October 2019 в 10:46
поделиться

Это то, что я всегда использую (хотя я не тестировал его на SL, только на WPF):

    /// <summary>
    /// This method registers a callback on a dependency object to be called
    /// when the value of the DP changes.
    /// </summary>
    /// <param name="owner">The owning object.</param>
    /// <param name="property">The DependencyProperty to watch.</param>
    /// <param name="handler">The action to call out when the DP changes.</param>
    public static void RegisterDepPropCallback(object owner, DependencyProperty property, EventHandler handler)
    {
        // FIXME: We could implement this as an extension, but let's not get
        // too Ruby-like
        var dpd = DependencyPropertyDescriptor.FromProperty(property, owner.GetType());
        dpd.AddValueChanged(owner, handler);
    }
-3
ответ дан 26 October 2019 в 10:46
поделиться

Единственное решение, которое я вижу, - это прослушивание события LayoutUpdated - да, я знаю, что оно часто вызывается. Однако обратите внимание, что в некоторых случаях он не будет вызываться, даже если FontSize или Style были изменены.

0
ответ дан 26 October 2019 в 10:46
поделиться

Это довольно отвратительный прием, но вы можете использовать двустороннюю привязку для моделирования этого.

т.е. иметь что-то вроде :

public class FontSizeListener {
    public double FontSize {
        get { return fontSize; }
        set { fontSize = value; OnFontSizeChanged (this, EventArgs.Empty); }
    }

    public event EventHandler FontSizeChanged;

    void OnFontSizeChanged (object sender, EventArgs e) {
      if (FontSizeChanged != null) FontSizeChanged (sender, e);
    }
}

затем создайте привязку, например:

<Canvas>
  <Canvas.Resources>
     <FontSizeListener x:Key="listener" />
  </Canvas.Resources>

  <MyControlSubclass FontSize="{Binding Mode=TwoWay, Source={StaticResource listener}, Path=FontSize}" />
</Canvas>

затем подключитесь к событию слушателя в вашем подклассе управления.

6
ответ дан 26 October 2019 в 10:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: